


'''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  _lowercase   :
   def __init__(	self					:			List[str]					,      SCREAMING_SNAKE_CASE_					:			str					,      SCREAMING_SNAKE_CASE_					:			Tuple=13					,      SCREAMING_SNAKE_CASE_					:			Union[str, Any]=32					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=2					,      SCREAMING_SNAKE_CASE_					:			int=3					,      SCREAMING_SNAKE_CASE_					:			Tuple=16					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]=[1, 2, 1]					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]=[2, 2, 4]					,      SCREAMING_SNAKE_CASE_					:			List[str]=2					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]=2.0					,      SCREAMING_SNAKE_CASE_					:			Union[str, Any]=True					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=0.0					,      SCREAMING_SNAKE_CASE_					:			Union[str, Any]=0.0					,      SCREAMING_SNAKE_CASE_					:			int=0.1					,      SCREAMING_SNAKE_CASE_					:			int="gelu"					,      SCREAMING_SNAKE_CASE_					:			List[Any]=False					,      SCREAMING_SNAKE_CASE_					:			Any=True					,      SCREAMING_SNAKE_CASE_					:			List[Any]=0.0_2					,      SCREAMING_SNAKE_CASE_					:			Dict=1e-5					,      SCREAMING_SNAKE_CASE_					:			Any=True					,      SCREAMING_SNAKE_CASE_					:			List[Any]=None					,      SCREAMING_SNAKE_CASE_					:			str=True					,      SCREAMING_SNAKE_CASE_					:			List[Any]=10					,      SCREAMING_SNAKE_CASE_					:			Any=8					,      )   ->       None:
        __snake_case    			=	parent
        __snake_case    			=	batch_size
        __snake_case    			=	image_size
        __snake_case    			=	patch_size
        __snake_case    			=	num_channels
        __snake_case    			=	embed_dim
        __snake_case    			=	depths
        __snake_case    			=	num_heads
        __snake_case    			=	window_size
        __snake_case    			=	mlp_ratio
        __snake_case    			=	qkv_bias
        __snake_case    			=	hidden_dropout_prob
        __snake_case    			=	attention_probs_dropout_prob
        __snake_case    			=	drop_path_rate
        __snake_case    			=	hidden_act
        __snake_case    			=	use_absolute_embeddings
        __snake_case    			=	patch_norm
        __snake_case    			=	layer_norm_eps
        __snake_case    			=	initializer_range
        __snake_case    			=	is_training
        __snake_case    			=	scope
        __snake_case    			=	use_labels
        __snake_case    			=	type_sequence_label_size
        __snake_case    			=	encoder_stride
   def a     (	self					:			Union[str, Any]			)   ->       Dict:
        __snake_case    			=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

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

        __snake_case    			=	self.get_config()

        return config, pixel_values, labels
   def a     (	self					:			Union[str, Any]			)   ->       Optional[Any]:
        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 a     (	self					:			List[Any]					,      SCREAMING_SNAKE_CASE_					:			Union[str, Any]					,      SCREAMING_SNAKE_CASE_					:			Tuple					,      SCREAMING_SNAKE_CASE_					:			Any			)   ->       Any:
        __snake_case    			=	TFSwinModel(config=SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	model(SCREAMING_SNAKE_CASE_			)

        __snake_case    			=	((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths			) - 1))
        __snake_case    			=	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 a     (	self					:			List[str]					,      SCREAMING_SNAKE_CASE_					:			Union[str, Any]					,      SCREAMING_SNAKE_CASE_					:			str					,      SCREAMING_SNAKE_CASE_					:			List[str]			)   ->       str:
        __snake_case    			=	TFSwinForMaskedImageModeling(config=SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	model(SCREAMING_SNAKE_CASE_			)
        self.parent.assertEqual(
            result.logits.shape					,      (self.batch_size, self.num_channels, self.image_size, self.image_size)			)

        # test greyscale images
        __snake_case    			=	1
        __snake_case    			=	TFSwinForMaskedImageModeling(SCREAMING_SNAKE_CASE_			)

        __snake_case    			=	floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
        __snake_case    			=	model(SCREAMING_SNAKE_CASE_			)
        self.parent.assertEqual(result.logits.shape					,      (self.batch_size, 1, self.image_size, self.image_size)			)
   def a     (	self					:			int					,      SCREAMING_SNAKE_CASE_					:			Optional[int]					,      SCREAMING_SNAKE_CASE_					:			Union[str, Any]					,      SCREAMING_SNAKE_CASE_					:			List[str]			)   ->       int:
        __snake_case    			=	self.type_sequence_label_size
        __snake_case    			=	TFSwinForImageClassification(SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	model(SCREAMING_SNAKE_CASE_					,      labels=SCREAMING_SNAKE_CASE_			)
        self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.type_sequence_label_size)			)

        # test greyscale images
        __snake_case    			=	1
        __snake_case    			=	TFSwinForImageClassification(SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
        __snake_case    			=	model(SCREAMING_SNAKE_CASE_			)
        self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.type_sequence_label_size)			)





   def a     (	self					:			Dict			)   ->       Dict:
        __snake_case    			=	self.prepare_config_and_inputs()
        __snake_case			,					__snake_case			,					__snake_case    			=	config_and_inputs
        __snake_case    			=	{'pixel_values': pixel_values}
        return config, inputs_dict




@require_tf
class  _lowercase   (  __lowercase	,				__lowercase	,				unittest.TestCase       ):
   _SCREAMING_SNAKE_CASE     :     List[str]									=  (
       (
           TFSwinModel,
           TFSwinForImageClassification,
           TFSwinForMaskedImageModeling,
       )
       if is_tf_available()
       else ()
   )
   _SCREAMING_SNAKE_CASE     :     int									=  (
       {"feature-extraction": TFSwinModel, "image-classification": TFSwinForImageClassification}
       if is_tf_available()
       else {}
   )

   _SCREAMING_SNAKE_CASE     :     Tuple									=  False
   _SCREAMING_SNAKE_CASE     :     List[str]									=  False
   _SCREAMING_SNAKE_CASE     :     List[str]									=  False
   _SCREAMING_SNAKE_CASE     :     List[str]									=  False
   def a     (	self					:			int			)   ->       int:
        __snake_case    			=	TFSwinModelTester(self			)
        __snake_case    			=	ConfigTester(self					,      config_class=SCREAMING_SNAKE_CASE_					,      embed_dim=37			)
   def a     (	self					:			Union[str, Any]			)   ->       Any:
        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 a     (	self					:			List[Any]			)   ->       Union[str, Any]:
        return
   def a     (	self					:			Tuple			)   ->       Any:
        __snake_case    			=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_			)
   def a     (	self					:			List[str]			)   ->       Tuple:
        __snake_case    			=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE_			)
   def a     (	self					:			Tuple			)   ->       str:
        __snake_case    			=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_			)
   @unittest.skip(reason='Swin does not use inputs_embeds'			)
   def a     (	self					:			Optional[Any]			)   ->       Optional[int]:
        pass
   def a     (	self					:			Optional[Any]			)   ->       Tuple:
        __snake_case			,					__snake_case    			=	self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             __snake_case    			=	model_class(SCREAMING_SNAKE_CASE_			)
             self.assertIsInstance(model.get_input_embeddings()					,      tf.keras.layers.Layer			)
             __snake_case    			=	model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_					,      tf.keras.layers.Dense			)			)
   def a     (	self					:			Optional[int]			)   ->       Any:
        __snake_case			,					__snake_case    			=	self.model_tester.prepare_config_and_inputs_for_common()

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

             __snake_case    			=	['pixel_values']
             self.assertListEqual(arg_names[:1]					,      SCREAMING_SNAKE_CASE_			)
   def a     (	self					:			int			)   ->       Any:
        __snake_case			,					__snake_case    			=	self.model_tester.prepare_config_and_inputs_for_common()
        __snake_case    			=	True

        for model_class in self.all_model_classes:
             __snake_case    			=	True
             __snake_case    			=	False
             __snake_case    			=	True
             __snake_case    			=	model_class(SCREAMING_SNAKE_CASE_			)
             __snake_case    			=	model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			)			)
             __snake_case    			=	outputs.attentions
             __snake_case    			=	len(self.model_tester.depths			)
             self.assertEqual(len(SCREAMING_SNAKE_CASE_			)					,      SCREAMING_SNAKE_CASE_			)

             # check that output_attentions also work using config
             del inputs_dict["output_attentions"]
             __snake_case    			=	True
             __snake_case    			=	config.window_size**2
             __snake_case    			=	model_class(SCREAMING_SNAKE_CASE_			)
             __snake_case    			=	model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			)			)
             __snake_case    			=	outputs.attentions
             self.assertEqual(len(SCREAMING_SNAKE_CASE_			)					,      SCREAMING_SNAKE_CASE_			)

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

             # Check attention is always last and order is fine
             __snake_case    			=	True
             __snake_case    			=	True
             __snake_case    			=	model_class(SCREAMING_SNAKE_CASE_			)
             __snake_case    			=	model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			)			)

             if hasattr(self.model_tester					,      'num_hidden_states_types'			):
                  __snake_case    			=	self.model_tester.num_hidden_states_types
             else:
                  # also another +1 for reshaped_hidden_states
                  __snake_case    			=	2
             self.assertEqual(out_len + added_hidden_states					,      len(SCREAMING_SNAKE_CASE_			)			)

             __snake_case    			=	outputs.attentions

             self.assertEqual(len(SCREAMING_SNAKE_CASE_			)					,      SCREAMING_SNAKE_CASE_			)

             self.assertListEqual(
                 list(self_attentions[0].shape[-3:]			)					,      [self.model_tester.num_heads[0], window_size_squared, window_size_squared]					,      )
   def a     (	self					:			List[Any]					,      SCREAMING_SNAKE_CASE_					:			List[Any]					,      SCREAMING_SNAKE_CASE_					:			Tuple					,      SCREAMING_SNAKE_CASE_					:			Union[str, Any]					,      SCREAMING_SNAKE_CASE_					:			Dict			)   ->       Any:
        __snake_case    			=	model_class(SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			)			)
        __snake_case    			=	outputs.hidden_states

        __snake_case    			=	getattr(
            self.model_tester					,      'expected_num_hidden_layers'					,      len(self.model_tester.depths			) + 1			)
        self.assertEqual(len(SCREAMING_SNAKE_CASE_			)					,      SCREAMING_SNAKE_CASE_			)

        # Swin has a different seq_length
        __snake_case    			=	to_atuple(config.patch_size			)

        __snake_case    			=	(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]					,      )

        __snake_case    			=	outputs.reshaped_hidden_states
        self.assertEqual(len(SCREAMING_SNAKE_CASE_			)					,      SCREAMING_SNAKE_CASE_			)

        __snake_case			,					__snake_case			,					__snake_case			,					__snake_case    			=	reshaped_hidden_states[0].shape

        __snake_case    			=	tf.reshape(reshaped_hidden_states[0]					,      (batch_size, num_channels, height * width)			)
        __snake_case    			=	tf.transpose(SCREAMING_SNAKE_CASE_					,      (0, 2, 1)			)

        self.assertListEqual(
            list(reshaped_hidden_states.shape[-2:]			)					,      [num_patches, self.model_tester.embed_dim]					,      )
   def a     (	self					:			Optional[Any]			)   ->       Any:
        __snake_case			,					__snake_case    			=	self.model_tester.prepare_config_and_inputs_for_common()

        __snake_case    			=	to_atuple(self.model_tester.image_size			)

        for model_class in self.all_model_classes:
             __snake_case    			=	True
             self.check_hidden_states_output(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			)

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             __snake_case    			=	True

             self.check_hidden_states_output(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			)
   def a     (	self					:			List[str]			)   ->       Dict:
        __snake_case			,					__snake_case    			=	self.model_tester.prepare_config_and_inputs_for_common()
        __snake_case    			=	3

        __snake_case    			=	to_atuple(self.model_tester.image_size			)
        __snake_case    			=	to_atuple(config.patch_size			)

        __snake_case    			=	image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
        __snake_case    			=	image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

        for model_class in self.all_model_classes:
             __snake_case    			=	True
             self.check_hidden_states_output(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_					,      (padded_height, padded_width)			)

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             __snake_case    			=	True
             self.check_hidden_states_output(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_					,      (padded_height, padded_width)			)





   @slow
   def a     (	self					:			Optional[Any]			)   ->       Optional[Any]:
        for model_name in TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             __snake_case    			=	TFSwinModel.from_pretrained(SCREAMING_SNAKE_CASE_			)
             self.assertIsNotNone(SCREAMING_SNAKE_CASE_			)




@require_vision
@require_tf
class  _lowercase   (  unittest.TestCase       ):
   @cached_property
   def a     (	self					:			Any			)   ->       Any:
        return (
            AutoImageProcessor.from_pretrained('microsoft/swin-tiny-patch4-window7-224'			)
            if is_vision_available()
            else None
        )





   @slow
   def a     (	self					:			Union[str, Any]			)   ->       List[Any]:
        __snake_case    			=	TFSwinForImageClassification.from_pretrained('microsoft/swin-tiny-patch4-window7-224'			)
        __snake_case    			=	self.default_image_processor

        __snake_case    			=	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
        __snake_case    			=	image_processor(images=SCREAMING_SNAKE_CASE_					,      return_tensors='tf'			)

        # forward pass
        __snake_case    			=	model(SCREAMING_SNAKE_CASE_			)

        # verify the logits
        __snake_case    			=	tf.TensorShape((1, 1000)			)
        self.assertEqual(outputs.logits.shape					,      SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	tf.constant([-0.0_9_4_8, -0.6_4_5_4, -0.0_9_2_1]			)
        self.assertTrue(np.allclose(outputs.logits[0, :3]					,      SCREAMING_SNAKE_CASE_					,      atol=1e-4			)			)








'''simple docstring'''




def      _a		(lowercase__ :      int	) -> int:






     """simple docstring"""
     return 1 if input_a == 0 else 0





def      _a		() -> None:






     """simple docstring"""
     assert not_gate(0	) == 1
     assert not_gate(1	) == 0


if __name__ == "__main__":
       print(not_gate(0))
       print(not_gate(1))




