"""simple docstring"""







import inspect
import unittest
from math import floor

from transformers import CvtConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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


if is_torch_available():
       import torch

       from transformers import CvtForImageClassification, CvtModel
       from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image

       from transformers import AutoImageProcessor







class  UpperCamelCase	(    lowercase_						):
   def     _UpperCAmelCase     (    self    )			->   List[Any]:


        '''simple docstring'''


        lowercase_			:       Tuple									=			self.config_class(**self.inputs_dict    )
        self.parent.assertTrue(hasattr(__UpperCamelCase  ,'embed_dim'    )    )
        self.parent.assertTrue(hasattr(__UpperCamelCase  ,'num_heads'    )    )







class  UpperCamelCase	:
   def __init__(    self  ,__UpperCamelCase  ,__UpperCamelCase=13  ,__UpperCamelCase=64  ,__UpperCamelCase=3  ,__UpperCamelCase=[16, 48, 96]  ,__UpperCamelCase=[1, 3, 6]  ,__UpperCamelCase=[1, 2, 10]  ,__UpperCamelCase=[7, 3, 3]  ,__UpperCamelCase=[4, 2, 2]  ,__UpperCamelCase=[2, 1, 1]  ,__UpperCamelCase=[2, 2, 2]  ,__UpperCamelCase=[False, False, True]  ,__UpperCamelCase=[0.0, 0.0, 0.0]  ,__UpperCamelCase=0.02  ,__UpperCamelCase=1e-12  ,__UpperCamelCase=True  ,__UpperCamelCase=True  ,__UpperCamelCase=2  ,)			->   int:


        '''simple docstring'''


        lowercase_			:       Tuple									=			parent
        lowercase_			:       Optional[Any]									=			batch_size
        lowercase_			:       Tuple									=			image_size
        lowercase_			:       Optional[int]									=			patch_sizes
        lowercase_			:       Union[str, Any]									=			patch_stride
        lowercase_			:       List[str]									=			patch_padding
        lowercase_			:       str									=			is_training
        lowercase_			:       str									=			use_labels
        lowercase_			:       List[str]									=			num_labels
        lowercase_			:       Tuple									=			num_channels
        lowercase_			:       Tuple									=			embed_dim
        lowercase_			:       str									=			num_heads
        lowercase_			:       List[Any]									=			stride_kv
        lowercase_			:       int									=			depth
        lowercase_			:       int									=			cls_token
        lowercase_			:       List[str]									=			attention_drop_rate
        lowercase_			:       List[Any]									=			initializer_range
        lowercase_			:       Optional[Any]									=			layer_norm_eps
   def     _UpperCAmelCase     (    self    )			->   int:


        '''simple docstring'''


        lowercase_			:       Optional[Any]									=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

        lowercase_			:       List[str]									=			None
        if self.use_labels:
             lowercase_			:       Tuple									=			ids_tensor([self.batch_size]  ,self.num_labels    )

        lowercase_			:       Optional[Any]									=			self.get_config()
        return config, pixel_values, labels
   def     _UpperCAmelCase     (    self    )			->   Optional[Any]:


        '''simple docstring'''


        return CvtConfig(
            image_size=self.image_size  ,num_labels=self.num_labels  ,num_channels=self.num_channels  ,embed_dim=self.embed_dim  ,num_heads=self.num_heads  ,patch_sizes=self.patch_sizes  ,patch_padding=self.patch_padding  ,patch_stride=self.patch_stride  ,stride_kv=self.stride_kv  ,depth=self.depth  ,cls_token=self.cls_token  ,attention_drop_rate=self.attention_drop_rate  ,initializer_range=self.initializer_range  ,)
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase  ,__UpperCamelCase  ,__UpperCamelCase    )			->   Tuple:


        '''simple docstring'''


        lowercase_			:       Any									=			CvtModel(config=__UpperCamelCase    )
        model.to(__UpperCamelCase    )
        model.eval()
        lowercase_			:       str									=			model(__UpperCamelCase    )
        lowercase_			:       List[Any]									=			(self.image_size, self.image_size)
        lowercase_							,						lowercase_			:       List[str]									=			image_size[0], image_size[1]
        for i in range(len(self.depth    )    ):
             lowercase_			:       Optional[Any]									=			floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1    )
             lowercase_			:       Dict									=			floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1    )
        self.parent.assertEqual(result.last_hidden_state.shape  ,(self.batch_size, self.embed_dim[-1], height, width)    )
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase  ,__UpperCamelCase  ,__UpperCamelCase    )			->   int:


        '''simple docstring'''


        lowercase_			:       List[str]									=			self.num_labels
        lowercase_			:       Dict									=			CvtForImageClassification(__UpperCamelCase    )
        model.to(__UpperCamelCase    )
        model.eval()
        lowercase_			:       Optional[int]									=			model(__UpperCamelCase  ,labels=__UpperCamelCase    )
        self.parent.assertEqual(result.logits.shape  ,(self.batch_size, self.num_labels)    )







   def     _UpperCAmelCase     (    self    )			->   int:


        '''simple docstring'''


        lowercase_			:       Dict									=			self.prepare_config_and_inputs()
        lowercase_							,						lowercase_							,						lowercase_			:       List[str]									=			config_and_inputs
        lowercase_			:       int									=			{'pixel_values': pixel_values}
        return config, inputs_dict







@require_torch
class  UpperCamelCase	(    lowercase_		,   lowercase_		,   unittest.TestCase						):
   lowercase							=						(CvtModel, CvtForImageClassification) if is_torch_available() else ()
   lowercase							=						(
       {'feature-extraction': CvtModel, 'image-classification': CvtForImageClassification}
       if is_torch_available()
       else {}
   )

   lowercase							=						False
   lowercase							=						False
   lowercase							=						False
   lowercase							=						False
   lowercase							=						False
   def     _UpperCAmelCase     (    self    )			->   List[Any]:


        '''simple docstring'''


        lowercase_			:       List[str]									=			CvtModelTester(self    )
        lowercase_			:       Union[str, Any]									=			ConfigTester(self  ,config_class=__UpperCamelCase  ,has_text_modality=__UpperCamelCase  ,hidden_size=37    )
   def     _UpperCAmelCase     (    self    )			->   str:


        '''simple docstring'''


        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     _UpperCAmelCase     (    self    )			->   Any:


        '''simple docstring'''


        return
   @unittest.skip(reason='Cvt does not output attentions'    )
   def     _UpperCAmelCase     (    self    )			->   Dict:


        '''simple docstring'''


        pass
   @unittest.skip(reason='Cvt does not use inputs_embeds'    )
   def     _UpperCAmelCase     (    self    )			->   int:


        '''simple docstring'''


        pass
   @unittest.skip(reason='Cvt does not support input and output embeddings'    )
   def     _UpperCAmelCase     (    self    )			->   str:


        '''simple docstring'''


        pass
   def     _UpperCAmelCase     (    self    )			->   Dict:


        '''simple docstring'''


        lowercase_							,						lowercase_			:       Optional[int]									=			self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             lowercase_			:       Dict									=			model_class(__UpperCamelCase    )
             lowercase_			:       Optional[int]									=			inspect.signature(model.forward    )
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             lowercase_			:       Union[str, Any]									=			[*signature.parameters.keys()]

             lowercase_			:       Tuple									=			['pixel_values']
             self.assertListEqual(arg_names[:1]  ,__UpperCamelCase    )
   def     _UpperCAmelCase     (    self    )			->   str:


        '''simple docstring'''


        lowercase_			:       Optional[Any]									=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__UpperCamelCase    )
   def     _UpperCAmelCase     (    self    )			->   int:


        '''simple docstring'''


        def check_hidden_states_output(__UpperCamelCase  ,__UpperCamelCase  ,__UpperCamelCase    ):
             lowercase_			:       Any									=			model_class(__UpperCamelCase    )
             model.to(__UpperCamelCase    )
             model.eval()

             with torch.no_grad():
                  lowercase_			:       Optional[Any]									=			model(**self._prepare_for_class(__UpperCamelCase  ,__UpperCamelCase    )    )

             lowercase_			:       Optional[Any]									=			outputs.hidden_states

             lowercase_			:       str									=			len(self.model_tester.depth    )
             self.assertEqual(len(__UpperCamelCase    )  ,__UpperCamelCase    )

             # verify the first hidden states (first block)
             self.assertListEqual(
                 list(hidden_states[0].shape[-3:]    )  ,[
                     self.model_tester.embed_dim[0],
                     self.model_tester.image_size // 4,
                     self.model_tester.image_size // 4,
                 ]  ,)

        lowercase_							,						lowercase_			:       Any									=			self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             lowercase_			:       Any									=			True
             check_hidden_states_output(__UpperCamelCase  ,__UpperCamelCase  ,__UpperCamelCase    )

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

             check_hidden_states_output(__UpperCamelCase  ,__UpperCamelCase  ,__UpperCamelCase    )
   def     _UpperCAmelCase     (    self    )			->   Union[str, Any]:


        '''simple docstring'''


        lowercase_			:       List[Any]									=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase    )
   @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'    )
   def     _UpperCAmelCase     (    self    )			->   Any:


        '''simple docstring'''


        pass







   @slow
   def     _UpperCAmelCase     (    self    )			->   List[Any]:


        '''simple docstring'''


        for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             lowercase_			:       str									=			CvtModel.from_pretrained(__UpperCamelCase    )
             self.assertIsNotNone(__UpperCamelCase    )






def     lowercase__( ):
     lowercase_			:       int									=			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
     return image







@require_torch
@require_vision
class  UpperCamelCase	(    unittest.TestCase						):
   @cached_property
   def     _UpperCAmelCase     (    self    )			->   Optional[int]:


        '''simple docstring'''


        return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )







   @slow
   def     _UpperCAmelCase     (    self    )			->   Any:


        '''simple docstring'''


        lowercase_			:       Optional[Any]									=			CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]    ).to(__UpperCamelCase    )

        lowercase_			:       List[str]									=			self.default_image_processor
        lowercase_			:       str									=			prepare_img()
        lowercase_			:       Union[str, Any]									=			image_processor(images=__UpperCamelCase  ,return_tensors='pt'    ).to(__UpperCamelCase    )

        # forward pass
        with torch.no_grad():
             lowercase_			:       List[str]									=			model(**__UpperCamelCase    )

        # verify the logits
        lowercase_			:       Union[str, Any]									=			torch.Size((1, 1000)    )
        self.assertEqual(outputs.logits.shape  ,__UpperCamelCase    )

        lowercase_			:       Optional[int]									=			torch.tensor([0.9285, 0.9015, -0.3150]    ).to(__UpperCamelCase    )

        self.assertTrue(torch.allclose(outputs.logits[0, :3]  ,__UpperCamelCase  ,atol=1e-4    )    )


"""simple docstring"""







from ...configuration_utils import PretrainedConfig
from ...utils import logging


__SCREAMING_SNAKE_CASE								=logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE								={
    "google/switch-base-8": "https://huggingface.co/google/switch-base-8/blob/main/config.json",
}







class  UpperCamelCase	(    lowercase_						):
   lowercase							=						'switch_transformers'
   lowercase							=						['past_key_values']
   lowercase							=						{'hidden_size': 'd_model', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'}
   def __init__(    self  ,__UpperCamelCase=3_2128  ,__UpperCamelCase=768  ,__UpperCamelCase=64  ,__UpperCamelCase=2048  ,__UpperCamelCase=64  ,__UpperCamelCase=12  ,__UpperCamelCase=3  ,__UpperCamelCase=12  ,__UpperCamelCase=3  ,__UpperCamelCase=12  ,__UpperCamelCase=8  ,__UpperCamelCase=False  ,__UpperCamelCase=0.01  ,__UpperCamelCase="float32"  ,__UpperCamelCase=False  ,__UpperCamelCase=32  ,__UpperCamelCase=128  ,__UpperCamelCase=0.1  ,__UpperCamelCase=1e-6  ,__UpperCamelCase=0.001  ,__UpperCamelCase=0.001  ,__UpperCamelCase=1.0  ,__UpperCamelCase="relu"  ,__UpperCamelCase=True  ,__UpperCamelCase=False  ,__UpperCamelCase=True  ,__UpperCamelCase=0  ,__UpperCamelCase=1  ,**__UpperCamelCase  ,)			->   str:


        '''simple docstring'''


        lowercase_			:       List[str]									=			vocab_size
        lowercase_			:       Optional[Any]									=			d_model
        lowercase_			:       Dict									=			d_kv
        lowercase_			:       Dict									=			d_ff

        lowercase_			:       str									=			num_sparse_encoder_layers

        lowercase_			:       List[str]									=			num_layers
        lowercase_			:       int									=			(
            num_decoder_layers if num_decoder_layers is not None else self.num_layers
        )  # default = symmetry
        lowercase_			:       Optional[Any]									=			num_sparse_decoder_layers

        # This tells us, each how many encoder layer we'll have to set a sparse layer.
        if self.num_sparse_encoder_layers > 0:
             lowercase_			:       Tuple									=			self.num_layers // self.num_sparse_encoder_layers
        else:
             lowercase_			:       Union[str, Any]									=			self.num_layers  # HACK: this will create 0 sparse layers

        # This tells us, each how many encoder layer we'll have to set a sparse layer.
        if self.num_sparse_decoder_layers > 0:
             lowercase_			:       Union[str, Any]									=			self.num_decoder_layers // self.num_sparse_decoder_layers
        else:
             lowercase_			:       List[Any]									=			self.num_decoder_layers  # HACK: this will create 0 sparse layers

        lowercase_			:       List[Any]									=			num_heads
        lowercase_			:       Dict									=			num_experts
        lowercase_			:       List[str]									=			expert_capacity
        lowercase_			:       Optional[Any]									=			router_bias
        lowercase_			:       Optional[Any]									=			router_jitter_noise
        if router_dtype not in ["float32", "float16", "bfloat16"]:
             raise ValueError(f'''`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}'''    )
        lowercase_			:       Optional[Any]									=			router_dtype

        lowercase_			:       Union[str, Any]									=			router_ignore_padding_tokens
        lowercase_			:       Any									=			relative_attention_num_buckets
        lowercase_			:       List[Any]									=			relative_attention_max_distance

        lowercase_			:       str									=			dropout_rate
        lowercase_			:       Any									=			layer_norm_epsilon
        lowercase_			:       Tuple									=			initializer_factor
        lowercase_			:       str									=			feed_forward_proj
        lowercase_			:       List[Any]									=			use_cache
        lowercase_			:       str									=			add_router_probs

        lowercase_			:       Tuple									=			router_z_loss_coef
        lowercase_			:       int									=			router_aux_loss_coef

        lowercase_			:       List[str]									=			self.feed_forward_proj.split('-'    )
        lowercase_			:       List[str]									=			act_info[-1]
        lowercase_			:       Optional[Any]									=			act_info[0] == 'gated'

        if len(__UpperCamelCase    ) > 1 and act_info[0] != "gated" or len(__UpperCamelCase    ) > 2:
             raise ValueError(
                 f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.'''
                 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. '
                 '\'gated-gelu\' or \'relu\''    )

        # for backwards compatibility
        if feed_forward_proj == "gated-gelu":
             lowercase_			:       Union[str, Any]									=			'gelu_new'

        super().__init__(
            pad_token_id=__UpperCamelCase  ,eos_token_id=__UpperCamelCase  ,is_encoder_decoder=__UpperCamelCase  ,**__UpperCamelCase  ,)

