

'''simple docstring'''



import collections
import inspect
import unittest

from transformers import DinatConfig
from transformers.testing_utils import require_natten, require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
   import torch
   from torch import nn

   from transformers import DinatBackbone, DinatForImageClassification, DinatModel
   from transformers.models.dinat.modeling_dinat import DINAT_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
   from PIL import Image

   from transformers import AutoImageProcessor

class 			SCREAMING_SNAKE_CASE					:






      '''simple docstring'''






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



          """simple docstring"""





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




      def 	__UpperCAmelCase			(					self :		Optional[Any]   ):



          """simple docstring"""





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

          _snake_case : List[str]												=		None
          if self.use_labels:
              _snake_case : Optional[Any]												=		ids_tensor([self.batch_size]     ,					self.num_labels   )

          _snake_case : str												=		self.get_config()

          return config, pixel_values, labels




      def 	__UpperCAmelCase			(					self :		Optional[Any]   ):



          """simple docstring"""





          return DinatConfig(
              num_labels=self.num_labels     ,					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     ,					kernel_size=self.kernel_size     ,					dilations=self.dilations     ,					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     ,					patch_norm=self.patch_norm     ,					layer_norm_eps=self.layer_norm_eps     ,					initializer_range=self.initializer_range     ,					out_features=self.out_features     ,					out_indices=self.out_indices     ,					)




      def 	__UpperCAmelCase			(					self :		Optional[Any]     ,					snake_case :		List[Any]     ,					snake_case :		str     ,					snake_case :		Optional[int]   ):



          """simple docstring"""





          _snake_case : str												=		DinatModel(config=snake_case   )
          model.to(snake_case   )
          model.eval()
          _snake_case : List[Any]												=		model(snake_case   )

          _snake_case : Tuple												=		(config.image_size // config.patch_size) // (2 ** (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_height, expected_width, expected_dim)   )




      def 	__UpperCAmelCase			(					self :		Any     ,					snake_case :		Union[str, Any]     ,					snake_case :		Optional[Any]     ,					snake_case :		str   ):



          """simple docstring"""





          _snake_case : Tuple												=		DinatForImageClassification(snake_case   )
          model.to(snake_case   )
          model.eval()
          _snake_case : Optional[int]												=		model(snake_case     ,					labels=snake_case   )
          self.parent.assertEqual(result.logits.shape     ,					(self.batch_size, self.num_labels)   )

          # test greyscale images
          _snake_case : Union[str, Any]												=		1
          _snake_case : Optional[int]												=		DinatForImageClassification(snake_case   )
          model.to(snake_case   )
          model.eval()

          _snake_case : List[str]												=		floats_tensor([self.batch_size, 1, self.image_size, self.image_size]   )
          _snake_case : List[Any]												=		model(snake_case   )
          self.parent.assertEqual(result.logits.shape     ,					(self.batch_size, self.num_labels)   )




      def 	__UpperCAmelCase			(					self :		str     ,					snake_case :		Optional[int]     ,					snake_case :		Dict     ,					snake_case :		Optional[Any]   ):



          """simple docstring"""





          _snake_case : int												=		DinatBackbone(config=snake_case   )
          model.to(snake_case   )
          model.eval()
          _snake_case : Dict												=		model(snake_case   )

          # verify hidden states
          self.parent.assertEqual(len(result.feature_maps   )     ,					len(config.out_features   )   )
          self.parent.assertListEqual(list(result.feature_maps[0].shape   )     ,					[self.batch_size, model.channels[0], 16, 16]   )

          # verify channels
          self.parent.assertEqual(len(model.channels   )     ,					len(config.out_features   )   )

          # verify backbone works with out_features=None
          _snake_case : Optional[Any]												=		None
          _snake_case : Any												=		DinatBackbone(config=snake_case   )
          model.to(snake_case   )
          model.eval()
          _snake_case : List[str]												=		model(snake_case   )

          # verify feature maps
          self.parent.assertEqual(len(result.feature_maps   )     ,					1   )
          self.parent.assertListEqual(list(result.feature_maps[0].shape   )     ,					[self.batch_size, model.channels[-1], 4, 4]   )

          # verify channels
          self.parent.assertEqual(len(model.channels   )     ,					1   )




      def 	__UpperCAmelCase			(					self :		Optional[int]   ):



          """simple docstring"""





          _snake_case : Any												=		self.prepare_config_and_inputs()
          _snake_case					,							_snake_case					,							_snake_case : Optional[int]												=		config_and_inputs
          _snake_case : Union[str, Any]												=		{'pixel_values': pixel_values}
          return config, inputs_dict



@require_natten
@require_torch
class 			SCREAMING_SNAKE_CASE					(							lowercase_      ,lowercase_      ,unittest.TestCase					):






      '''simple docstring'''






      SCREAMING_SNAKE_CASE__ :				Any    =				(
          (
              DinatModel,
              DinatForImageClassification,
              DinatBackbone,
          )
          if is_torch_available()
          else ()
      )
      SCREAMING_SNAKE_CASE__ :				Tuple    =				(
          {'''feature-extraction''': DinatModel, '''image-classification''': DinatForImageClassification}
          if is_torch_available()
          else {}
      )
      SCREAMING_SNAKE_CASE__ :				Tuple    =				False

      SCREAMING_SNAKE_CASE__ :				Tuple    =				False
      SCREAMING_SNAKE_CASE__ :				Optional[Any]    =				False
      SCREAMING_SNAKE_CASE__ :				Union[str, Any]    =				False
      SCREAMING_SNAKE_CASE__ :				int    =				False




      def 	__UpperCAmelCase			(					self :		str   ):



          """simple docstring"""





          _snake_case : Optional[int]												=		DinatModelTester(self   )
          _snake_case : Tuple												=		ConfigTester(self     ,					config_class=snake_case     ,					embed_dim=37   )




      def 	__UpperCAmelCase			(					self :		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 :		int   ):



          """simple docstring"""





          return




      def 	__UpperCAmelCase			(					self :		Tuple   ):



          """simple docstring"""





          _snake_case : List[Any]												=		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*snake_case   )




      def 	__UpperCAmelCase			(					self :		Any   ):



          """simple docstring"""





          _snake_case : Optional[Any]												=		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*snake_case   )




      def 	__UpperCAmelCase			(					self :		Tuple   ):



          """simple docstring"""





          _snake_case : Union[str, Any]												=		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_backbone(*snake_case   )




      @unittest.skip(reason='Dinat does not use inputs_embeds'   )
      def 	__UpperCAmelCase			(					self :		List[str]   ):



          """simple docstring"""





          pass




      @unittest.skip(reason='Dinat does not use feedforward chunking'   )
      def 	__UpperCAmelCase			(					self :		Tuple   ):



          """simple docstring"""





          pass




      def 	__UpperCAmelCase			(					self :		Dict   ):



          """simple docstring"""





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

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




      def 	__UpperCAmelCase			(					self :		str   ):



          """simple docstring"""





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

          for model_class in self.all_model_classes:
              _snake_case : str												=		model_class(snake_case   )
              _snake_case : List[str]												=		inspect.signature(model.forward   )
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              _snake_case : Optional[int]												=		[*signature.parameters.keys()]

              _snake_case : Union[str, Any]												=		['pixel_values']
              self.assertListEqual(arg_names[:1]     ,					snake_case   )




      def 	__UpperCAmelCase			(					self :		Union[str, Any]   ):



          """simple docstring"""





          self.skipTest('Dinat\'s attention operation is handled entirely by NATTEN.'   )




      def 	__UpperCAmelCase			(					self :		List[str]     ,					snake_case :		Dict     ,					snake_case :		Any     ,					snake_case :		Optional[Any]     ,					snake_case :		List[str]   ):



          """simple docstring"""





          _snake_case : Union[str, Any]												=		model_class(snake_case   )
          model.to(snake_case   )
          model.eval()

          with torch.no_grad():
              _snake_case : List[str]												=		model(**self._prepare_for_class(snake_case     ,					snake_case   )   )

          _snake_case : Optional[int]												=		outputs.hidden_states

          _snake_case : Tuple												=		getattr(
              self.model_tester     ,					'expected_num_hidden_layers'     ,					len(self.model_tester.depths   ) + 1   )
          self.assertEqual(len(snake_case   )     ,					snake_case   )

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

          _snake_case : Union[str, Any]												=		image_size[0] // patch_size[0]
          _snake_case : Tuple												=		image_size[1] // patch_size[1]

          self.assertListEqual(
              list(hidden_states[0].shape[-3:]   )     ,					[height, width, self.model_tester.embed_dim]     ,					)

          if model_class.__name__ != "DinatBackbone":
              _snake_case : Dict												=		outputs.reshaped_hidden_states
              self.assertEqual(len(snake_case   )     ,					snake_case   )

              _snake_case					,							_snake_case					,							_snake_case					,							_snake_case : List[str]												=		reshaped_hidden_states[0].shape
              _snake_case : Optional[Any]												=		(
                  reshaped_hidden_states[0].view(snake_case     ,					snake_case     ,					snake_case     ,					snake_case   ).permute(0     ,					2     ,					3     ,					1   )
              )
              self.assertListEqual(
                  list(reshaped_hidden_states.shape[-3:]   )     ,					[height, width, self.model_tester.embed_dim]     ,					)




      def 	__UpperCAmelCase			(					self :		Optional[int]   ):



          """simple docstring"""





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

          _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)
          )

          for model_class in self.all_model_classes:
              _snake_case : List[str]												=		True
              self.check_hidden_states_output(snake_case     ,					snake_case     ,					snake_case     ,					snake_case   )

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

              self.check_hidden_states_output(snake_case     ,					snake_case     ,					snake_case     ,					snake_case   )




      @slow
      def 	__UpperCAmelCase			(					self :		int   ):



          """simple docstring"""





          for model_name in DINAT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              _snake_case : List[str]												=		DinatModel.from_pretrained(snake_case   )
              self.assertIsNotNone(snake_case   )




      def 	__UpperCAmelCase			(					self :		List[str]   ):



          """simple docstring"""





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

          _snake_case : Tuple												=		_config_zero_init(snake_case   )
          for model_class in self.all_model_classes:
              _snake_case : str												=		model_class(config=snake_case   )
              for name, param in model.named_parameters():
                  if "embeddings" not in name and param.requires_grad:
                      self.assertIn(
                          ((param.data.mean() * 1e9).round() / 1e9).item()     ,					[0.0, 1.0]     ,					msg=F"""Parameter {name} of model {model_class} seems not properly initialized"""     ,					)



@require_natten
@require_vision
@require_torch
class 			SCREAMING_SNAKE_CASE					(							unittest.TestCase					):






      '''simple docstring'''






      @cached_property
      def 	__UpperCAmelCase			(					self :		str   ):



          """simple docstring"""





          return AutoImageProcessor.from_pretrained('shi-labs/dinat-mini-in1k-224'   ) if is_vision_available() else None




      @slow
      def 	__UpperCAmelCase			(					self :		Any   ):



          """simple docstring"""





          _snake_case : str												=		DinatForImageClassification.from_pretrained('shi-labs/dinat-mini-in1k-224'   ).to(snake_case   )
          _snake_case : List[str]												=		self.default_image_processor

          _snake_case : Optional[Any]												=		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
          _snake_case : int												=		image_processor(images=snake_case     ,					return_tensors='pt'   ).to(snake_case   )

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

          # verify the logits
          _snake_case : List[str]												=		torch.Size((1, 1000)   )
          self.assertEqual(outputs.logits.shape     ,					snake_case   )
          _snake_case : List[str]												=		torch.tensor([-0.1545, -0.7667, 0.4642]   ).to(snake_case   )
          self.assertTrue(torch.allclose(outputs.logits[0, :3]     ,					snake_case     ,					atol=1e-4   )   )



@require_torch
@require_natten
class 			SCREAMING_SNAKE_CASE					(							unittest.TestCase      ,lowercase_					):






      '''simple docstring'''






      SCREAMING_SNAKE_CASE__ :				List[Any]    =				(DinatBackbone,) if is_torch_available() else ()
      SCREAMING_SNAKE_CASE__ :				Tuple    =				DinatConfig




      def 	__UpperCAmelCase			(					self :		List[str]   ):



          """simple docstring"""





          _snake_case : Union[str, Any]												=		DinatModelTester(self   )






'''simple docstring'''



def   lowerCamelCase__       (      a__			,      a__)		->    int:



    """simple docstring"""







    _snake_case : Tuple												=		0
    for ele in arr:
        total_sum += product_sum(a__			,      depth + 1) if isinstance(a__			,      a__) else ele
    return total_sum * depth

def   lowerCamelCase__       (      a__)		->    int:



    """simple docstring"""







    return product_sum(a__			,      1)


if __name__ == "__main__":
   import doctest

   doctest.testmod()



