


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 					__lowerCamelCase	:







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






            '''simple docstring'''




            __UpperCamelCase				=	parent
            __UpperCamelCase				=	batch_size
            __UpperCamelCase				=	seq_length
            __UpperCamelCase				=	is_training
            __UpperCamelCase				=	use_input_mask
            __UpperCamelCase				=	use_token_type_ids
            __UpperCamelCase				=	use_labels
            __UpperCamelCase				=	vocab_size
            __UpperCamelCase				=	hidden_size
            __UpperCamelCase				=	num_hidden_layers
            __UpperCamelCase				=	num_attention_heads
            __UpperCamelCase				=	intermediate_size
            __UpperCamelCase				=	hidden_act
            __UpperCamelCase				=	hidden_dropout_prob
            __UpperCamelCase				=	attention_probs_dropout_prob
            __UpperCamelCase				=	max_position_embeddings
            __UpperCamelCase				=	type_vocab_size
            __UpperCamelCase				=	type_sequence_label_size
            __UpperCamelCase				=	initializer_range
            __UpperCamelCase				=	num_labels
            __UpperCamelCase				=	num_choices
            __UpperCamelCase				=	scope







       def 						snake_case_					(	self:				Dict			):






            '''simple docstring'''




            __UpperCamelCase				=	ids_tensor([self.batch_size, self.seq_length],self.vocab_size			)

            __UpperCamelCase				=	None
            if self.use_input_mask:
                 __UpperCamelCase				=	random_attention_mask([self.batch_size, self.seq_length]			)

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

            __UpperCamelCase				=	None
            __UpperCamelCase				=	None
            __UpperCamelCase				=	None
            if self.use_labels:
                 __UpperCamelCase				=	ids_tensor([self.batch_size],self.type_sequence_label_size			)
                 __UpperCamelCase				=	ids_tensor([self.batch_size, self.seq_length],self.num_labels			)
                 __UpperCamelCase				=	ids_tensor([self.batch_size],self.num_choices			)
                 __UpperCamelCase				=	ids_tensor([self.batch_size, self.seq_length],1			)

            __UpperCamelCase				=	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:				Union[str, Any]			):






            '''simple docstring'''




            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=A_,initializer_range=self.initializer_range,)







       def 						snake_case_					(	self:				Optional[Any]			):






            '''simple docstring'''




            (
                (
                __UpperCamelCase
            ),  (
                __UpperCamelCase
            ),  (
                __UpperCamelCase
            ),  (
                __UpperCamelCase
            ),  (
                __UpperCamelCase
            ),  (
                __UpperCamelCase
            ),  (
                __UpperCamelCase
            ),  (
                __UpperCamelCase
            ),  
            )				=	self.prepare_config_and_inputs()

            __UpperCamelCase				=	True
            __UpperCamelCase				=	floats_tensor([self.batch_size, self.seq_length, self.hidden_size]			)
            __UpperCamelCase				=	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:				Optional[int],A_:				str,A_:				Tuple,A_:				str,A_:				Any,A_:				Tuple,A_:				Union[str, Any],A_:				str,A_:				str,):






            '''simple docstring'''




            __UpperCamelCase				=	ElectraModel(config=A_			)
            model.to(A_			)
            model.eval()
            __UpperCamelCase				=	model(A_,attention_mask=A_,token_type_ids=A_			)
            __UpperCamelCase				=	model(A_,token_type_ids=A_			)
            __UpperCamelCase				=	model(A_			)
            self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, self.seq_length, self.hidden_size)			)







       def 						snake_case_					(	self:				List[str],A_:				Any,A_:				Optional[int],A_:				Tuple,A_:				Union[str, Any],A_:				Union[str, Any],A_:				int,A_:				List[str],A_:				List[Any],A_:				Optional[Any],):






            '''simple docstring'''




            __UpperCamelCase				=	True
            __UpperCamelCase				=	ElectraModel(A_			)
            model.to(A_			)
            model.eval()
            __UpperCamelCase				=	model(
                A_,attention_mask=A_,token_type_ids=A_,encoder_hidden_states=A_,encoder_attention_mask=A_,)
            __UpperCamelCase				=	model(
                A_,attention_mask=A_,token_type_ids=A_,encoder_hidden_states=A_,)
            __UpperCamelCase				=	model(A_,attention_mask=A_,token_type_ids=A_			)
            self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, self.seq_length, self.hidden_size)			)







       def 						snake_case_					(	self:				List[Any],A_:				str,A_:				Dict,A_:				List[Any],A_:				Tuple,A_:				Union[str, Any],A_:				Optional[Any],A_:				Tuple,A_:				Optional[int],):






            '''simple docstring'''




            __UpperCamelCase				=	ElectraForMaskedLM(config=A_			)
            model.to(A_			)
            model.eval()
            __UpperCamelCase				=	model(A_,attention_mask=A_,token_type_ids=A_,labels=A_			)
            self.parent.assertEqual(result.logits.shape,(self.batch_size, self.seq_length, self.vocab_size)			)







       def 						snake_case_					(	self:				int,A_:				Union[str, Any],A_:				Optional[int],A_:				List[Any],A_:				Optional[int],A_:				Dict,A_:				Dict,A_:				List[Any],A_:				Optional[Any],A_:				str,):






            '''simple docstring'''




            __UpperCamelCase				=	ElectraForCausalLM(config=A_			)
            model.to(A_			)
            model.eval()
            __UpperCamelCase				=	model(A_,attention_mask=A_,token_type_ids=A_,labels=A_			)
            self.parent.assertEqual(result.logits.shape,(self.batch_size, self.seq_length, self.vocab_size)			)







       def 						snake_case_					(	self:				str,A_:				List[Any],A_:				str,A_:				Optional[Any],A_:				Optional[Any],A_:				Union[str, Any],A_:				List[Any],A_:				int,A_:				str,):






            '''simple docstring'''




            __UpperCamelCase				=	self.num_labels
            __UpperCamelCase				=	ElectraForTokenClassification(config=A_			)
            model.to(A_			)
            model.eval()
            __UpperCamelCase				=	model(A_,attention_mask=A_,token_type_ids=A_,labels=A_			)
            self.parent.assertEqual(result.logits.shape,(self.batch_size, self.seq_length, self.num_labels)			)







       def 						snake_case_					(	self:				Optional[int],A_:				Union[str, Any],A_:				List[str],A_:				Any,A_:				str,A_:				List[Any],A_:				List[str],A_:				Union[str, Any],A_:				Optional[Any],):






            '''simple docstring'''




            __UpperCamelCase				=	self.num_labels
            __UpperCamelCase				=	ElectraForPreTraining(config=A_			)
            model.to(A_			)
            model.eval()
            __UpperCamelCase				=	model(A_,attention_mask=A_,token_type_ids=A_,labels=A_			)
            self.parent.assertEqual(result.logits.shape,(self.batch_size, self.seq_length)			)







       def 						snake_case_					(	self:				Dict,A_:				Tuple,A_:				Optional[int],A_:				List[Any],A_:				Dict,A_:				Optional[Any],A_:				Any,A_:				Optional[Any],A_:				List[Any],):






            '''simple docstring'''




            __UpperCamelCase				=	self.num_labels
            __UpperCamelCase				=	ElectraForSequenceClassification(A_			)
            model.to(A_			)
            model.eval()
            __UpperCamelCase				=	model(A_,attention_mask=A_,token_type_ids=A_,labels=A_			)
            self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_labels)			)







       def 						snake_case_					(	self:				List[Any],A_:				Optional[int],A_:				List[str],A_:				Optional[Any],A_:				Optional[Any],A_:				Tuple,A_:				str,A_:				int,A_:				List[str],):






            '''simple docstring'''




            __UpperCamelCase				=	ElectraForQuestionAnswering(config=A_			)
            model.to(A_			)
            model.eval()
            __UpperCamelCase				=	model(
                A_,attention_mask=A_,token_type_ids=A_,start_positions=A_,end_positions=A_,)
            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:				Tuple,A_:				int,A_:				List[Any],A_:				Tuple,A_:				List[Any],A_:				str,A_:				Optional[Any],A_:				int,A_:				List[str],):






            '''simple docstring'''




            __UpperCamelCase				=	self.num_choices
            __UpperCamelCase				=	ElectraForMultipleChoice(config=A_			)
            model.to(A_			)
            model.eval()
            __UpperCamelCase				=	input_ids.unsqueeze(1			).expand(-1,self.num_choices,-1			).contiguous()
            __UpperCamelCase				=	token_type_ids.unsqueeze(1			).expand(-1,self.num_choices,-1			).contiguous()
            __UpperCamelCase				=	input_mask.unsqueeze(1			).expand(-1,self.num_choices,-1			).contiguous()
            __UpperCamelCase				=	model(
                A_,attention_mask=A_,token_type_ids=A_,labels=A_,)
            self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_choices)			)







       def 						snake_case_					(	self:				Optional[Any]			):






            '''simple docstring'''




            __UpperCamelCase				=	self.prepare_config_and_inputs()
            (
                (
                __UpperCamelCase
            ),  (
                __UpperCamelCase
            ),  (
                __UpperCamelCase
            ),  (
                __UpperCamelCase
            ),  (
                __UpperCamelCase
            ),  (
                __UpperCamelCase
            ),  (
                __UpperCamelCase
            ),  (
                __UpperCamelCase
            ),  
            )				=	config_and_inputs
            __UpperCamelCase				=	{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
            return config, inputs_dict



@require_torch
class 					__lowerCamelCase	(_a							,     _a							,     unittest.TestCase		):
       _lowercase    							=      (
           (
               ElectraModel,
               ElectraForPreTraining,
               ElectraForMaskedLM,
               ElectraForCausalLM,
               ElectraForMultipleChoice,
               ElectraForTokenClassification,
               ElectraForSequenceClassification,
               ElectraForQuestionAnswering,
           )
           if is_torch_available()
           else ()
       )
       _lowercase    							=      (
           {
               """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 {}
       )
       _lowercase    							=      True







       def 						snake_case_					(	self:				Union[str, Any],A_:				Union[str, Any],A_:				Optional[Any],A_:				str=False			):






            '''simple docstring'''




            __UpperCamelCase				=	super()._prepare_for_class(A_,A_,return_labels=A_			)

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







       def 						snake_case_					(	self:				Dict			):






            '''simple docstring'''




            __UpperCamelCase				=	ElectraModelTester(self			)
            __UpperCamelCase				=	ConfigTester(self,config_class=A_,hidden_size=37			)







       def 						snake_case_					(	self:				Optional[Any]			):






            '''simple docstring'''




            self.config_tester.run_common_tests()







       def 						snake_case_					(	self:				Any			):






            '''simple docstring'''




            __UpperCamelCase				=	self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_electra_model(*A_			)







       def 						snake_case_					(	self:				List[Any]			):






            '''simple docstring'''




            __UpperCamelCase				=	self.model_tester.prepare_config_and_inputs_for_decoder()
            self.model_tester.create_and_check_electra_model_as_decoder(*A_			)







       def 						snake_case_					(	self:				Optional[Any]			):






            '''simple docstring'''




            __UpperCamelCase				=	self.model_tester.prepare_config_and_inputs()
            for type in ["absolute", "relative_key", "relative_key_query"]:
                 __UpperCamelCase				=	type
                 self.model_tester.create_and_check_electra_model(*A_			)







       def 						snake_case_					(	self:				Tuple			):






            '''simple docstring'''




            __UpperCamelCase				=	self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_electra_for_masked_lm(*A_			)







       def 						snake_case_					(	self:				Tuple			):






            '''simple docstring'''




            __UpperCamelCase				=	self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_electra_for_token_classification(*A_			)







       def 						snake_case_					(	self:				str			):






            '''simple docstring'''




            __UpperCamelCase				=	self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_electra_for_pretraining(*A_			)







       def 						snake_case_					(	self:				Tuple			):






            '''simple docstring'''




            __UpperCamelCase				=	self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_electra_for_sequence_classification(*A_			)







       def 						snake_case_					(	self:				str			):






            '''simple docstring'''




            __UpperCamelCase				=	self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_electra_for_question_answering(*A_			)







       def 						snake_case_					(	self:				Optional[int]			):






            '''simple docstring'''




            __UpperCamelCase				=	self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_electra_for_multiple_choice(*A_			)







       @slow
       def 						snake_case_					(	self:				Any			):






            '''simple docstring'''




            for model_name in ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 __UpperCamelCase				=	ElectraModel.from_pretrained(A_			)
                 self.assertIsNotNone(A_			)







       def 						snake_case_					(	self:				str			):






            '''simple docstring'''




            __UpperCamelCase				=	self.model_tester.prepare_config_and_inputs_for_decoder()
            self.model_tester.create_and_check_electra_for_causal_lm(*A_			)



@require_torch
class 					__lowerCamelCase	(unittest.TestCase		):







       @slow
       def 						snake_case_					(	self:				Any			):






            '''simple docstring'''




            __UpperCamelCase				=	ElectraModel.from_pretrained('google/electra-small-discriminator'			)
            __UpperCamelCase				=	torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]			)
            __UpperCamelCase				=	torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]			)
            __UpperCamelCase				=	model(A_,attention_mask=A_			)[0]
            __UpperCamelCase				=	torch.Size((1, 11, 256)			)
            self.assertEqual(output.shape,A_			)
            __UpperCamelCase				=	torch.tensor(
                [[[0.4_4_7_1, 0.6_8_2_1, -0.3_2_6_5], [0.4_6_2_7, 0.5_2_5_5, -0.3_6_6_8], [0.4_5_3_2, 0.3_3_1_3, -0.4_3_4_4]]]			)

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






# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_torch_available,
)


__snake_case     =		{
    '''configuration_convnextv2''': [
        '''CONVNEXTV2_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''ConvNextV2Config''',
    ]
}

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    __snake_case     =		[
        '''CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST''',
        '''ConvNextV2ForImageClassification''',
        '''ConvNextV2Model''',
        '''ConvNextV2PreTrainedModel''',
        '''ConvNextV2Backbone''',
    ]


if TYPE_CHECKING:
    from .configuration_convnextva import (
        CONVNEXTV2_PRETRAINED_CONFIG_ARCHIVE_MAP,
        ConvNextVaConfig,
    )

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_convnextva import (
            CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST,
            ConvNextVaBackbone,
            ConvNextVaForImageClassification,
            ConvNextVaModel,
            ConvNextVaPreTrainedModel,
        )

else:
    import sys

    __snake_case     =		_LazyModule(__name__, globals()['''__file__'''], _import_structure)


