




"""simple docstring"""


import collections
import inspect
import unittest
from typing import Dict, List, Tuple

from transformers import MaskFormerSwinConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device
from transformers.utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
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 torch import nn

     from transformers import MaskFormerSwinBackbone
     from transformers.models.maskformer import MaskFormerSwinModel






class 					lowercase:







 '''simple docstring'''





 def __init__(				self:		Any,      a_:		Union[str, Any],      a_:		Dict=13,      a_:		Optional[Any]=32,      a_:		Any=2,      a_:		Any=3,      a_:		Optional[Any]=16,      a_:		List[str]=[1, 2, 1],      a_:		int=[2, 2, 4],      a_:		Dict=2,      a_:		Optional[int]=2.0,      a_:		Union[str, Any]=True,      a_:		Optional[Any]=0.0,      a_:		Optional[int]=0.0,      a_:		Union[str, Any]=0.1,      a_:		str="gelu",      a_:		int=False,      a_:		Union[str, Any]=True,      a_:		Dict=0.02,      a_:		List[Any]=1E-5,      a_:		int=True,      a_:		Union[str, Any]=None,      a_:		Optional[int]=True,      a_:		List[Any]=10,      a_:		Tuple=8,      a_:		Optional[Any]=["stage1", "stage2", "stage3"],      a_:		Union[str, Any]=[1, 2, 3],      ):




   '''simple docstring'''



   _snake_case							:		str								=  parent
   _snake_case							:		Optional[int]								=  batch_size
   _snake_case							:		Any								=  image_size
   _snake_case							:		int								=  patch_size
   _snake_case							:		Union[str, Any]								=  num_channels
   _snake_case							:		int								=  embed_dim
   _snake_case							:		Optional[Any]								=  depths
   _snake_case							:		Tuple								=  num_heads
   _snake_case							:		Union[str, Any]								=  window_size
   _snake_case							:		List[Any]								=  mlp_ratio
   _snake_case							:		Union[str, Any]								=  qkv_bias
   _snake_case							:		List[Any]								=  hidden_dropout_prob
   _snake_case							:		Dict								=  attention_probs_dropout_prob
   _snake_case							:		Union[str, Any]								=  drop_path_rate
   _snake_case							:		str								=  hidden_act
   _snake_case							:		Union[str, Any]								=  use_absolute_embeddings
   _snake_case							:		Optional[Any]								=  patch_norm
   _snake_case							:		Any								=  layer_norm_eps
   _snake_case							:		Union[str, Any]								=  initializer_range
   _snake_case							:		Union[str, Any]								=  is_training
   _snake_case							:		Optional[Any]								=  scope
   _snake_case							:		Union[str, Any]								=  use_labels
   _snake_case							:		Union[str, Any]								=  type_sequence_label_size
   _snake_case							:		str								=  encoder_stride
   _snake_case							:		List[Any]								=  out_features
   _snake_case							:		Tuple								=  out_indices


 def  UpperCamelCase_   (				self:		str		):




   '''simple docstring'''



   _snake_case							:		str								=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

   _snake_case							:		Tuple								=  None
   if self.use_labels:
     _snake_case							:		Optional[Any]								=  ids_tensor([self.batch_size],      self.type_sequence_label_size		)

   _snake_case							:		List[str]								=  self.get_config()

   return config, pixel_values, labels


 def  UpperCamelCase_   (				self:		str		):




   '''simple docstring'''



   return MaskFormerSwinConfig(
       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,      out_features=self.out_features,      out_indices=self.out_indices,      )


 def  UpperCamelCase_   (				self:		str,      a_:		List[str],      a_:		List[str],      a_:		str		):




   '''simple docstring'''



   _snake_case							:		str								=  MaskFormerSwinModel(config=a_		)
   model.to(a_		)
   model.eval()
   _snake_case							:		Any								=  model(a_		)

   _snake_case							:		List[str]								=  ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths		) - 1))
   _snake_case							:		List[str]								=  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  UpperCamelCase_   (				self:		Dict,      a_:		Tuple,      a_:		Tuple,      a_:		Any		):




   '''simple docstring'''



   _snake_case							:		int								=  MaskFormerSwinBackbone(config=a_		)
   model.to(a_		)
   model.eval()
   _snake_case							:		str								=  model(a_		)

   # verify feature maps
   self.parent.assertEqual(len(result.feature_maps		),      len(config.out_features		)		)
   self.parent.assertListEqual(list(result.feature_maps[0].shape		),      [13, 16, 16, 16]		)

   # verify channels
   self.parent.assertEqual(len(model.channels		),      len(config.out_features		)		)
   self.parent.assertListEqual(model.channels,      [16, 32, 64]		)

   # verify ValueError
   with self.parent.assertRaises(a_		):
     _snake_case							:		Optional[Any]								=  ["""stem"""]
     _snake_case							:		Tuple								=  MaskFormerSwinBackbone(config=a_		)


 def  UpperCamelCase_   (				self:		Tuple		):




   '''simple docstring'''



   _snake_case							:		Any								=  self.prepare_config_and_inputs()
   _snake_case		,					_snake_case		,					_snake_case							:		List[Any]								=  config_and_inputs
   _snake_case							:		Optional[Any]								=  {"""pixel_values""": pixel_values}
   return config, inputs_dict







@require_torch
class 					lowercase(     __a       ,			__a       ,			unittest.TestCase ):







 '''simple docstring'''





 lowercase__ 					=					(
     (
         MaskFormerSwinModel,
         MaskFormerSwinBackbone,
     )
     if is_torch_available()
     else ()
 )
 lowercase__ 					=					{"feature-extraction": MaskFormerSwinModel} if is_torch_available() else {}
 lowercase__ 					=					False
 lowercase__ 					=					False
 lowercase__ 					=					False
 lowercase__ 					=					False
 lowercase__ 					=					False


 def  UpperCamelCase_   (				self:		Tuple		):




   '''simple docstring'''



   _snake_case							:		List[Any]								=  MaskFormerSwinModelTester(self		)
   _snake_case							:		List[str]								=  ConfigTester(self,      config_class=a_,      embed_dim=37		)


 @require_torch_multi_gpu
 @unittest.skip(
     reason=(
         """`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with"""
         """ `nn.DataParallel`"""
     )		)
 def  UpperCamelCase_   (				self:		int		):




   '''simple docstring'''



   pass


 def  UpperCamelCase_   (				self:		Optional[Any]		):




   '''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:		Tuple		):




   '''simple docstring'''



   return


 def  UpperCamelCase_   (				self:		Dict		):




   '''simple docstring'''



   _snake_case							:		Optional[Any]								=  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*a_		)


 def  UpperCamelCase_   (				self:		Tuple		):




   '''simple docstring'''



   _snake_case							:		List[Any]								=  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_backbone(*a_		)


 @unittest.skip("""Swin does not use inputs_embeds"""		)
 def  UpperCamelCase_   (				self:		Any		):




   '''simple docstring'''



   pass


 @unittest.skip("""Swin does not support feedforward chunking"""		)
 def  UpperCamelCase_   (				self:		Optional[Any]		):




   '''simple docstring'''



   pass


 def  UpperCamelCase_   (				self:		Dict		):




   '''simple docstring'''



   _snake_case		,					_snake_case							:		int								=  self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     _snake_case							:		Optional[int]								=  model_class(a_		)
     self.assertIsInstance(model.get_input_embeddings(),      (nn.Module)		)
     _snake_case							:		Optional[Any]								=  model.get_output_embeddings()
     self.assertTrue(x is None or isinstance(a_,      nn.Linear		)		)


 def  UpperCamelCase_   (				self:		List[str]		):




   '''simple docstring'''



   _snake_case		,					_snake_case							:		List[Any]								=  self.model_tester.prepare_config_and_inputs_for_common()

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

     _snake_case							:		List[Any]								=  ["""pixel_values"""]
     self.assertListEqual(arg_names[:1],      a_		)


 @unittest.skip(reason="""MaskFormerSwin is only used as backbone and doesn't support output_attentions"""		)
 def  UpperCamelCase_   (				self:		List[Any]		):




   '''simple docstring'''



   pass


 @unittest.skip(reason="""MaskFormerSwin is only used as an internal backbone"""		)
 def  UpperCamelCase_   (				self:		str		):




   '''simple docstring'''



   pass


 def  UpperCamelCase_   (				self:		int,      a_:		str,      a_:		Dict,      a_:		Union[str, Any],      a_:		Union[str, Any]		):




   '''simple docstring'''



   _snake_case							:		Any								=  model_class(a_		)
   model.to(a_		)
   model.eval()

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

   _snake_case							:		Optional[Any]								=  outputs.hidden_states

   _snake_case							:		Any								=  getattr(
       self.model_tester,      """expected_num_hidden_layers""",      len(self.model_tester.depths		) + 1		)
   self.assertEqual(len(a_		),      a_		)

   # Swin has a different seq_length
   _snake_case							:		int								=  (
       config.patch_size
       if isinstance(config.patch_size,      collections.abc.Iterable		)
       else (config.patch_size, config.patch_size)
   )

   _snake_case							:		int								=  (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],      )


 def  UpperCamelCase_   (				self:		List[Any]		):




   '''simple docstring'''



   _snake_case		,					_snake_case							:		int								=  self.model_tester.prepare_config_and_inputs_for_common()

   _snake_case							:		Any								=  (
       self.model_tester.image_size
       if isinstance(self.model_tester.image_size,      collections.abc.Iterable		)
       else (self.model_tester.image_size, self.model_tester.image_size)
   )

   for model_class in self.all_model_classes:
     _snake_case							:		Tuple								=  True
     self.check_hidden_states_output(a_,      a_,      a_,      a_		)

     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     _snake_case							:		Optional[Any]								=  True

     self.check_hidden_states_output(a_,      a_,      a_,      a_		)


 def  UpperCamelCase_   (				self:		Optional[Any]		):




   '''simple docstring'''



   _snake_case		,					_snake_case							:		int								=  self.model_tester.prepare_config_and_inputs_for_common()
   _snake_case							:		str								=  3

   _snake_case							:		List[str]								=  (
       self.model_tester.image_size
       if isinstance(self.model_tester.image_size,      collections.abc.Iterable		)
       else (self.model_tester.image_size, self.model_tester.image_size)
   )
   _snake_case							:		List[Any]								=  (
       config.patch_size
       if isinstance(config.patch_size,      collections.abc.Iterable		)
       else (config.patch_size, config.patch_size)
   )

   _snake_case							:		List[str]								=  image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
   _snake_case							:		Tuple								=  image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

   for model_class in self.all_model_classes:
     _snake_case							:		Any								=  True
     self.check_hidden_states_output(a_,      a_,      a_,      (padded_height, padded_width)		)

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


 @unittest.skip(reason="""MaskFormerSwin doesn't have pretrained checkpoints"""		)
 def  UpperCamelCase_   (				self:		int		):




   '''simple docstring'''



   pass


 @unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin"""		)
 def  UpperCamelCase_   (				self:		Dict		):




   '''simple docstring'''



   pass


 @unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin"""		)
 def  UpperCamelCase_   (				self:		int		):




   '''simple docstring'''



   pass


 def  UpperCamelCase_   (				self:		str		):




   '''simple docstring'''



   _snake_case		,					_snake_case							:		str								=  self.model_tester.prepare_config_and_inputs_for_common()

   def set_nan_tensor_to_zero(a_:		List[str]		):
     _snake_case							:		Union[str, Any]								=  0
     return t

   def check_equivalence(a_:		List[Any],      a_:		List[Any],      a_:		List[str],      a_:		List[str]={}		):
     with torch.no_grad():
       _snake_case							:		Any								=  model(**a_,      return_dict=a_,      **a_		)
       _snake_case							:		int								=  model(**a_,      return_dict=a_,      **a_		).to_tuple()

       def recursive_check(a_:		Union[str, Any],      a_:		Tuple		):
         if isinstance(a_,      (List, Tuple)		):
           for tuple_iterable_value, dict_iterable_value in zip(a_,      a_		):
             recursive_check(a_,      a_		)
         elif isinstance(a_,      a_		):
           for tuple_iterable_value, dict_iterable_value in zip(
               tuple_object.values(),      dict_object.values()		):
             recursive_check(a_,      a_		)
         elif tuple_object is None:
           return
         else:
           self.assertTrue(
               torch.allclose(
                   set_nan_tensor_to_zero(a_		),      set_nan_tensor_to_zero(a_		),      atol=1E-5		),      msg=(
                   """Tuple and dict output are not equal. Difference:"""
                   f" {torch.max(torch.abs(tuple_object - dict_object		)		)}. Tuple has `nan`:"
                   f" {torch.isnan(a_		).any()} and `inf`: {torch.isinf(a_		)}. Dict has"
                   f" `nan`: {torch.isnan(a_		).any()} and `inf`: {torch.isinf(a_		)}."
               ),      )

       recursive_check(a_,      a_		)

   for model_class in self.all_model_classes:
     _snake_case							:		Tuple								=  model_class(a_		)
     model.to(a_		)
     model.eval()

     _snake_case							:		int								=  self._prepare_for_class(a_,      a_		)
     _snake_case							:		str								=  self._prepare_for_class(a_,      a_		)
     check_equivalence(a_,      a_,      a_		)

     _snake_case							:		str								=  self._prepare_for_class(a_,      a_,      return_labels=a_		)
     _snake_case							:		str								=  self._prepare_for_class(a_,      a_,      return_labels=a_		)
     check_equivalence(a_,      a_,      a_		)

     _snake_case							:		Tuple								=  self._prepare_for_class(a_,      a_		)
     _snake_case							:		str								=  self._prepare_for_class(a_,      a_		)
     check_equivalence(a_,      a_,      a_,      {"""output_hidden_states""": True}		)

     _snake_case							:		int								=  self._prepare_for_class(a_,      a_,      return_labels=a_		)
     _snake_case							:		Optional[int]								=  self._prepare_for_class(a_,      a_,      return_labels=a_		)
     check_equivalence(a_,      a_,      a_,      {"""output_hidden_states""": True}		)







@require_torch
class 					lowercase(     unittest.TestCase       ,			__a ):







 '''simple docstring'''





 lowercase__ 					=					(MaskFormerSwinBackbone,) if is_torch_available() else ()
 lowercase__ 					=					MaskFormerSwinConfig


 def  UpperCamelCase_   (				self:		int		):




   '''simple docstring'''



   _snake_case							:		List[Any]								=  MaskFormerSwinModelTester(self		)


 def  UpperCamelCase_   (				self:		str		):




   '''simple docstring'''



   _snake_case		,					_snake_case							:		List[Any]								=  self.model_tester.prepare_config_and_inputs_for_common()
   _snake_case							:		Tuple								=  inputs_dict["""pixel_values"""].shape[0]

   for backbone_class in self.all_model_classes:
     _snake_case							:		Any								=  backbone_class(a_		)
     backbone.to(a_		)
     backbone.eval()

     _snake_case							:		Union[str, Any]								=  backbone(**a_		)

     # Test default outputs and verify feature maps
     self.assertIsInstance(outputs.feature_maps,      a_		)
     self.assertTrue(len(outputs.feature_maps		) == len(backbone.channels		)		)
     for feature_map, n_channels in zip(outputs.feature_maps,      backbone.channels		):
       self.assertTrue(feature_map.shape[:2],      (batch_size, n_channels)		)
     self.assertIsNone(outputs.hidden_states		)
     self.assertIsNone(outputs.attentions		)

     # Test output_hidden_states=True
     _snake_case							:		List[str]								=  backbone(**a_,      output_hidden_states=a_		)
     self.assertIsNotNone(outputs.hidden_states		)
     self.assertTrue(len(outputs.hidden_states		),      len(backbone.stage_names		)		)
     # We skip the stem layer
     for hidden_states, n_channels in zip(outputs.hidden_states[1:],      backbone.channels		):
       for hidden_state in hidden_states:
         # Hidden states are in the format (batch_size, (height * width), n_channels)
         _snake_case		,					_snake_case		,					_snake_case							:		Any								=  hidden_state.shape
         self.assertTrue((h_batch_size, h_n_channels),      (batch_size, n_channels)		)

            # Test output_attentions=True
     if self.has_attentions:
       _snake_case							:		Dict								=  backbone(**a_,      output_attentions=a_		)
       self.assertIsNotNone(outputs.attentions		)





from __future__ import annotations

import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import require_tf, require_vision, slow
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 import TFViTForImageClassification, TFViTModel


if is_vision_available():
     from PIL import Image

     from transformers import ViTImageProcessor


class  A						:







    """simple docstring"""





    def __init__(      self :       Union[str, Any],lowercase_ :       Any,lowercase_ :       Union[str, Any]=1_3,lowercase_ :       Tuple=3_0,lowercase_ :       List[Any]=2,lowercase_ :       Optional[int]=3,lowercase_ :       Union[str, Any]=True,lowercase_ :       Tuple=True,lowercase_ :       Any=3_2,lowercase_ :       List[str]=2,lowercase_ :       Optional[int]=4,lowercase_ :       Union[str, Any]=3_7,lowercase_ :       Tuple="gelu",lowercase_ :       str=0.1,lowercase_ :       Tuple=0.1,lowercase_ :       Union[str, Any]=1_0,lowercase_ :       int=0.02,lowercase_ :       List[Any]=3,lowercase_ :       Any=None,)->    Dict:





        '''simple docstring'''







        A__          =   parent
        A__          =   batch_size
        A__          =   image_size
        A__          =   patch_size
        A__          =   num_channels
        A__          =   is_training
        A__          =   use_labels
        A__          =   hidden_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__          =   type_sequence_label_size
        A__          =   initializer_range
        A__          =   scope

        # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
        A__          =   (image_size // patch_size) ** 2
        A__          =   num_patches + 1


    def 						snake_case__     (      self :       int		)->    List[str]:





        '''simple docstring'''







        A__          =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

        A__          =   None
        if self.use_labels:
            A__          =   ids_tensor([self.batch_size],self.type_sequence_label_size		)

        A__          =   self.get_config()

        return config, pixel_values, labels


    def 						snake_case__     (      self :       Tuple		)->    List[Any]:





        '''simple docstring'''







        return ViTConfig(
            image_size=self.image_size,patch_size=self.patch_size,num_channels=self.num_channels,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,is_decoder=lowercase_,initializer_range=self.initializer_range,)


    def 						snake_case__     (      self :       List[str],lowercase_ :       int,lowercase_ :       Union[str, Any],lowercase_ :       Tuple		)->    Optional[Any]:





        '''simple docstring'''







        A__          =   TFViTModel(config=lowercase_		)
        A__          =   model(lowercase_,training=lowercase_		)
        self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, self.seq_length, self.hidden_size)		)

        # Test with an image with different size than the one specified in config.
        A__          =   self.image_size // 2
        A__          =   pixel_values[:, :, :image_size, :image_size]
        A__          =   model(lowercase_,interpolate_pos_encoding=lowercase_,training=lowercase_		)
        A__          =   (image_size // self.patch_size) ** 2 + 1
        self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, seq_length, self.hidden_size)		)


    def 						snake_case__     (      self :       List[Any],lowercase_ :       List[Any],lowercase_ :       List[Any],lowercase_ :       List[Any]		)->    Dict:





        '''simple docstring'''







        A__          =   self.type_sequence_label_size
        A__          =   TFViTForImageClassification(lowercase_		)
        A__          =   model(lowercase_,labels=lowercase_,training=lowercase_		)
        self.parent.assertEqual(result.logits.shape,(self.batch_size, self.type_sequence_label_size)		)

        # Test with an image with different size than the one specified in config.
        A__          =   self.image_size // 2
        A__          =   pixel_values[:, :, :image_size, :image_size]
        A__          =   model(lowercase_,interpolate_pos_encoding=lowercase_,training=lowercase_		)
        self.parent.assertEqual(result.logits.shape,(self.batch_size, self.type_sequence_label_size)		)

        # test greyscale images
        A__          =   1
        A__          =   TFViTForImageClassification(lowercase_		)
        A__          =   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
        A__          =   model(lowercase_		)
        self.parent.assertEqual(result.logits.shape,(self.batch_size, self.type_sequence_label_size)		)


    def 						snake_case__     (      self :       Any		)->    Optional[Any]:





        '''simple docstring'''







        A__          =   self.prepare_config_and_inputs()
        A__      ,						A__      ,						A__          =   config_and_inputs
        A__          =   {'pixel_values': pixel_values}
        return config, inputs_dict




@require_tf
class  A						(							_UpperCAmelCase    ,							_UpperCAmelCase    ,							unittest.TestCase ):







    """simple docstring"""





    lowerCamelCase			=							(TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
    lowerCamelCase			=							(
        {'feature-extraction': TFViTModel, 'image-classification': TFViTForImageClassification}
        if is_tf_available()
        else {}
    )

    lowerCamelCase			=							False
    lowerCamelCase			=							False
    lowerCamelCase			=							False


    def 						snake_case__     (      self :       int		)->    List[Any]:





        '''simple docstring'''







        A__          =   TFViTModelTester(self		)
        A__          =   ConfigTester(self,config_class=lowercase_,has_text_modality=lowercase_,hidden_size=3_7		)


    def 						snake_case__     (      self :       Any		)->    Optional[Any]:





        '''simple docstring'''







        self.config_tester.run_common_tests()


    @unittest.skip(reason='ViT does not use inputs_embeds'		)
    def 						snake_case__     (      self :       Optional[Any]		)->    str:





        '''simple docstring'''







        pass


    @unittest.skip(reason='ViT does not use inputs_embeds'		)
    def 						snake_case__     (      self :       Any		)->    int:





        '''simple docstring'''







        pass


    def 						snake_case__     (      self :       str		)->    Dict:





        '''simple docstring'''







        A__      ,						A__          =   self.model_tester.prepare_config_and_inputs_for_common()

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


    def 						snake_case__     (      self :       int		)->    List[str]:





        '''simple docstring'''







        A__      ,						A__          =   self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            A__          =   model_class(lowercase_		)
            A__          =   inspect.signature(model.call		)
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            A__          =   [*signature.parameters.keys()]

            A__          =   ['pixel_values']
            self.assertListEqual(arg_names[:1],lowercase_		)


    def 						snake_case__     (      self :       Union[str, Any]		)->    Optional[Any]:





        '''simple docstring'''







        A__          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowercase_		)


    def 						snake_case__     (      self :       Optional[Any]		)->    Optional[Any]:





        '''simple docstring'''







        A__          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowercase_		)


    @slow
    def 						snake_case__     (      self :       Union[str, Any]		)->    Union[str, Any]:





        '''simple docstring'''







        A__          =   TFViTModel.from_pretrained('google/vit-base-patch16-224'		)
        self.assertIsNotNone(lowercase_		)




def 						_snake_case(    )							->      str:





    '''simple docstring'''






    A__          =   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'      )
    return image


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







    """simple docstring"""





    @cached_property
    def 						snake_case__     (      self :       List[Any]		)->    str:





        '''simple docstring'''







        return ViTImageProcessor.from_pretrained('google/vit-base-patch16-224'		) if is_vision_available() else None


    @slow
    def 						snake_case__     (      self :       Any		)->    Dict:





        '''simple docstring'''







        A__          =   TFViTForImageClassification.from_pretrained('google/vit-base-patch16-224'		)

        A__          =   self.default_image_processor
        A__          =   prepare_img()
        A__          =   image_processor(images=lowercase_,return_tensors='tf'		)

        # forward pass
        A__          =   model(**lowercase_		)

        # verify the logits
        A__          =   tf.TensorShape((1, 1_0_0_0)		)
        self.assertEqual(outputs.logits.shape,lowercase_		)

        A__          =   tf.constant([-0.2_744, 0.8_215, -0.0_836]		)

        tf.debugging.assert_near(outputs.logits[0, :3],lowercase_,atol=1E-4		)

