
'''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 			__A					:
 def __init__( self      :     List[str]					, lowerCamelCase      :     Optional[int]					, lowerCamelCase      :     Any=13					, lowerCamelCase      :     str=32					, lowerCamelCase      :     Union[str, Any]=2					, lowerCamelCase      :     Any=3					, lowerCamelCase      :     Union[str, Any]=16					, lowerCamelCase      :     Tuple=[1, 2, 1]					, lowerCamelCase      :     Optional[Any]=[2, 2, 4]					, lowerCamelCase      :     str=2					, lowerCamelCase      :     List[Any]=2.0					, lowerCamelCase      :     Union[str, Any]=True					, lowerCamelCase      :     Optional[int]=0.0					, lowerCamelCase      :     Tuple=0.0					, lowerCamelCase      :     Optional[int]=0.1					, lowerCamelCase      :     Union[str, Any]="gelu"					, lowerCamelCase      :     Tuple=False					, lowerCamelCase      :     List[str]=True					, lowerCamelCase      :     Optional[int]=0.02					, lowerCamelCase      :     int=1e-5					, lowerCamelCase      :     Dict=True					, lowerCamelCase      :     Dict=None					, lowerCamelCase      :     Any=True					, lowerCamelCase      :     List[str]=10					, lowerCamelCase      :     int=8					, ):



   """simple docstring"""





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



   """simple docstring"""





   __A		:  Union[str, Any]       				=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

   __A		:  Any       				=		None
   if self.use_labels:
     __A		:  Union[str, Any]       				=		ids_tensor([self.batch_size]					, self.type_sequence_label_size							)

   __A		:  str       				=		self.get_config()

   return config, pixel_values, labels
 def 		lowercase_( self      :     Dict							):



   """simple docstring"""





   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 		lowercase_( self      :     List[str]					, lowerCamelCase      :     str					, lowerCamelCase      :     List[str]					, lowerCamelCase      :     Dict							):



   """simple docstring"""





   __A		:  int       				=		TFSwinModel(config=lowerCamelCase							)
   __A		:  str       				=		model(lowerCamelCase							)

   __A		:  Tuple       				=		((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths							) - 1))
   __A		:  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 		lowercase_( self      :     Tuple					, lowerCamelCase      :     List[Any]					, lowerCamelCase      :     Tuple					, lowerCamelCase      :     List[Any]							):



   """simple docstring"""





   __A		:  Optional[Any]       				=		TFSwinForMaskedImageModeling(config=lowerCamelCase							)
   __A		:  int       				=		model(lowerCamelCase							)
   self.parent.assertEqual(
       result.logits.shape					, (self.batch_size, self.num_channels, self.image_size, self.image_size)							)

   # test greyscale images
   __A		:  List[str]       				=		1
   __A		:  Any       				=		TFSwinForMaskedImageModeling(lowerCamelCase							)

   __A		:  List[str]       				=		floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
   __A		:  str       				=		model(lowerCamelCase							)
   self.parent.assertEqual(result.logits.shape					, (self.batch_size, 1, self.image_size, self.image_size)							)
 def 		lowercase_( self      :     List[Any]					, lowerCamelCase      :     Dict					, lowerCamelCase      :     Tuple					, lowerCamelCase      :     List[Any]							):



   """simple docstring"""





   __A		:  str       				=		self.type_sequence_label_size
   __A		:  int       				=		TFSwinForImageClassification(lowerCamelCase							)
   __A		:  List[str]       				=		model(lowerCamelCase					, labels=lowerCamelCase							)
   self.parent.assertEqual(result.logits.shape					, (self.batch_size, self.type_sequence_label_size)							)

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






 def 		lowercase_( self      :     Any							):



   """simple docstring"""





   __A		:  Union[str, Any]       				=		self.prepare_config_and_inputs()
   __A				,       __A				,       __A		:  Dict       				=		config_and_inputs
   __A		:  Union[str, Any]       				=		{"""pixel_values""": pixel_values}
   return config, inputs_dict







@require_tf
class 			__A					(			__snake_case     ,    __snake_case     ,    unittest.TestCase      ):
 lowerCamelCase												=(
     (
         TFSwinModel,
         TFSwinForImageClassification,
         TFSwinForMaskedImageModeling,
     )
     if is_tf_available()
     else ()
 )
 lowerCamelCase												=(
     {'''feature-extraction''': TFSwinModel, '''image-classification''': TFSwinForImageClassification}
     if is_tf_available()
     else {}
 )

 lowerCamelCase												=False
 lowerCamelCase												=False
 lowerCamelCase												=False
 lowerCamelCase												=False
 def 		lowercase_( self      :     List[str]							):



   """simple docstring"""





   __A		:  Any       				=		TFSwinModelTester(self							)
   __A		:  Optional[Any]       				=		ConfigTester(self					, config_class=lowerCamelCase					, embed_dim=37							)
 def 		lowercase_( self      :     Optional[int]							):



   """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 		lowercase_( self      :     List[Any]							):



   """simple docstring"""





   return
 def 		lowercase_( self      :     List[str]							):



   """simple docstring"""





   __A		:  str       				=		self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*lowerCamelCase							)
 def 		lowercase_( self      :     str							):



   """simple docstring"""





   __A		:  Any       				=		self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_masked_image_modeling(*lowerCamelCase							)
 def 		lowercase_( self      :     Any							):



   """simple docstring"""





   __A		:  Tuple       				=		self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*lowerCamelCase							)
 @unittest.skip(reason="""Swin does not use inputs_embeds"""							)
 def 		lowercase_( self      :     Tuple							):



   """simple docstring"""





   pass
 def 		lowercase_( self      :     Optional[Any]							):



   """simple docstring"""





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

   for model_class in self.all_model_classes:
     __A		:  Union[str, Any]       				=		model_class(lowerCamelCase							)
     self.assertIsInstance(model.get_input_embeddings()					, tf.keras.layers.Layer							)
     __A		:  Optional[Any]       				=		model.get_output_embeddings()
     self.assertTrue(x is None or isinstance(lowerCamelCase					, tf.keras.layers.Dense							)							)
 def 		lowercase_( self      :     List[str]							):



   """simple docstring"""





   __A				,       __A		:  Tuple       				=		self.model_tester.prepare_config_and_inputs_for_common()

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

     __A		:  int       				=		["""pixel_values"""]
     self.assertListEqual(arg_names[:1]					, lowerCamelCase							)
 def 		lowercase_( self      :     str							):



   """simple docstring"""





   __A				,       __A		:  Optional[int]       				=		self.model_tester.prepare_config_and_inputs_for_common()
   __A		:  Optional[Any]       				=		True

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

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

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

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

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

     __A		:  List[str]       				=		outputs.attentions

     self.assertEqual(len(lowerCamelCase							)					, lowerCamelCase							)

     self.assertListEqual(
         list(self_attentions[0].shape[-3:]							)					, [self.model_tester.num_heads[0], window_size_squared, window_size_squared]					, )
 def 		lowercase_( self      :     Optional[int]					, lowerCamelCase      :     Optional[int]					, lowerCamelCase      :     Dict					, lowerCamelCase      :     Dict					, lowerCamelCase      :     List[Any]							):



   """simple docstring"""





   __A		:  Union[str, Any]       				=		model_class(lowerCamelCase							)
   __A		:  Tuple       				=		model(**self._prepare_for_class(lowerCamelCase					, lowerCamelCase							)							)
   __A		:  Tuple       				=		outputs.hidden_states

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

   # Swin has a different seq_length
   __A		:  Union[str, Any]       				=		to_atuple(config.patch_size							)

   __A		:  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]					, )

   __A		:  int       				=		outputs.reshaped_hidden_states
   self.assertEqual(len(lowerCamelCase							)					, lowerCamelCase							)

   __A				,       __A				,       __A				,       __A		:  int       				=		reshaped_hidden_states[0].shape

   __A		:  Tuple       				=		tf.reshape(reshaped_hidden_states[0]					, (batch_size, num_channels, height * width)							)
   __A		:  str       				=		tf.transpose(lowerCamelCase					, (0, 2, 1)							)

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



   """simple docstring"""





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

   __A		:  Tuple       				=		to_atuple(self.model_tester.image_size							)

   for model_class in self.all_model_classes:
     __A		:  int       				=		True
     self.check_hidden_states_output(lowerCamelCase					, lowerCamelCase					, lowerCamelCase					, lowerCamelCase							)

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

     self.check_hidden_states_output(lowerCamelCase					, lowerCamelCase					, lowerCamelCase					, lowerCamelCase							)
 def 		lowercase_( self      :     Union[str, Any]							):



   """simple docstring"""





   __A				,       __A		:  Any       				=		self.model_tester.prepare_config_and_inputs_for_common()
   __A		:  Any       				=		3

   __A		:  List[Any]       				=		to_atuple(self.model_tester.image_size							)
   __A		:  Dict       				=		to_atuple(config.patch_size							)

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

   for model_class in self.all_model_classes:
     __A		:  List[str]       				=		True
     self.check_hidden_states_output(lowerCamelCase					, lowerCamelCase					, lowerCamelCase					, (padded_height, padded_width)							)

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






 @slow
 def 		lowercase_( self      :     List[Any]							):



   """simple docstring"""





   for model_name in TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     __A		:  Any       				=		TFSwinModel.from_pretrained(lowerCamelCase							)
     self.assertIsNotNone(lowerCamelCase							)







@require_vision
@require_tf
class 			__A					(			unittest.TestCase      ):
 @cached_property
 def 		lowercase_( self      :     int							):



   """simple docstring"""





   return (
       AutoImageProcessor.from_pretrained("""microsoft/swin-tiny-patch4-window7-224"""							)
       if is_vision_available()
       else None
   )






 @slow
 def 		lowercase_( self      :     Dict							):



   """simple docstring"""





   __A		:  List[str]       				=		TFSwinForImageClassification.from_pretrained("""microsoft/swin-tiny-patch4-window7-224"""							)
   __A		:  Tuple       				=		self.default_image_processor

   __A		:  Union[str, Any]       				=		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""							)
   __A		:  List[str]       				=		image_processor(images=lowerCamelCase					, return_tensors="""tf"""							)

   # forward pass
   __A		:  str       				=		model(lowerCamelCase							)

   # verify the logits
   __A		:  List[str]       				=		tf.TensorShape((1, 10_00)							)
   self.assertEqual(outputs.logits.shape					, lowerCamelCase							)
   __A		:  Tuple       				=		tf.constant([-0.0_948, -0.6_454, -0.0_921]							)
   self.assertTrue(np.allclose(outputs.logits[0, :3]					, lowerCamelCase					, atol=1e-4							)							)






"""simple docstring"""






from typing import Callable
def 		A_	(   __UpperCamelCase     :				Callable				):

		def wrapper(__UpperCamelCase     :				Optional[Any]				):
				lowercase										=							function_with_docstring.__doc__
				return target_function

		return wrapper