






import copy
import inspect
import unittest

from transformers import PretrainedConfig, SwiftFormerConfig
from transformers.testing_utils import (
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available

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 SwiftFormerForImageClassification, SwiftFormerModel
     from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import ViTImageProcessor







class 			snake_case__   :

       '''simple docstring'''



       def __init__(							self			,						a__			,						a__=13			,						a__=3			,						a__=True			,						a__=True			,						a__=0.1			,						a__=0.1			,						a__=2_24			,						a__=10_00			,						a__=[3, 3, 6, 4]			,						a__=[48, 56, 1_12, 2_20]			,						) ->      List[str]:






            '''simple docstring'''





            __snake_case			:Any          =						parent
            __snake_case			:List[str]          =						batch_size
            __snake_case			:Dict          =						num_channels
            __snake_case			:Union[str, Any]          =						is_training
            __snake_case			:Optional[int]          =						use_labels
            __snake_case			:Optional[int]          =						hidden_dropout_prob
            __snake_case			:Tuple          =						attention_probs_dropout_prob
            __snake_case			:Optional[Any]          =						num_labels
            __snake_case			:str          =						image_size
            __snake_case			:Dict          =						layer_depths
            __snake_case			:List[Any]          =						embed_dims



       def 					__lowercase						(							self    ) ->      Any:






            '''simple docstring'''





            __snake_case			:Dict          =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

            __snake_case			:Dict          =						None
            if self.use_labels:
                 __snake_case			:Any          =						ids_tensor([self.batch_size]			,						self.num_labels    )

            __snake_case			:List[Any]          =						self.get_config()

            return config, pixel_values, labels



       def 					__lowercase						(							self    ) ->      int:






            '''simple docstring'''





            return SwiftFormerConfig(
                depths=self.layer_depths			,						embed_dims=self.embed_dims			,						mlp_ratio=4			,						downsamples=[True, True, True, True]			,						hidden_act="""gelu"""			,						num_labels=self.num_labels			,						down_patch_size=3			,						down_stride=2			,						down_pad=1			,						drop_rate=0.0			,						drop_path_rate=0.0			,						use_layer_scale=_UpperCAmelCase			,						layer_scale_init_value=1e-5			,						)



       def 					__lowercase						(							self			,						a__			,						a__			,						a__    ) ->      Union[str, Any]:






            '''simple docstring'''





            __snake_case			:Optional[int]          =						SwiftFormerModel(config=_UpperCAmelCase    )
            model.to(_UpperCAmelCase    )
            model.eval()
            __snake_case			:Union[str, Any]          =						model(_UpperCAmelCase    )
            self.parent.assertEqual(result.last_hidden_state.shape			,						(self.batch_size, self.embed_dims[-1], 7, 7)    )



       def 					__lowercase						(							self			,						a__			,						a__			,						a__    ) ->      Union[str, Any]:






            '''simple docstring'''





            __snake_case			:str          =						self.num_labels
            __snake_case			:List[Any]          =						SwiftFormerForImageClassification(_UpperCAmelCase    )
            model.to(_UpperCAmelCase    )
            model.eval()
            __snake_case			:Optional[Any]          =						model(_UpperCAmelCase			,						labels=_UpperCAmelCase    )
            self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.num_labels)    )

            __snake_case			:Optional[int]          =						SwiftFormerForImageClassification(_UpperCAmelCase    )
            model.to(_UpperCAmelCase    )
            model.eval()

            __snake_case			:Dict          =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )
            __snake_case			:Optional[Any]          =						model(_UpperCAmelCase    )
            self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.num_labels)    )



       def 					__lowercase						(							self    ) ->      Optional[int]:






            '''simple docstring'''





            ((__snake_case)       , (__snake_case)       , (__snake_case))			:List[str]          =						self.prepare_config_and_inputs()
            __snake_case			:Dict          =						{"""pixel_values""": pixel_values}
            return config, inputs_dict







@require_torch
class 			snake_case__   (							lowercase_	,    lowercase_	,    unittest.TestCase):

       '''simple docstring'''
       lowerCamelCase							:				Optional[int] 				= (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else ()
       lowerCamelCase							:				str 				= (
           {"feature-extraction": SwiftFormerModel, "image-classification": SwiftFormerForImageClassification}
           if is_torch_available()
           else {}
       )

       lowerCamelCase							:				List[str] 				= False
       lowerCamelCase							:				str 				= False
       lowerCamelCase							:				str 				= False
       lowerCamelCase							:				Tuple 				= False
       lowerCamelCase							:				str 				= False



       def 					__lowercase						(							self    ) ->      int:






            '''simple docstring'''





            __snake_case			:List[str]          =						SwiftFormerModelTester(self    )
            __snake_case			:str          =						ConfigTester(
                self			,						config_class=_UpperCAmelCase			,						has_text_modality=_UpperCAmelCase			,						hidden_size=37			,						num_attention_heads=12			,						num_hidden_layers=12			,						)



       def 					__lowercase						(							self    ) ->      int:






            '''simple docstring'''





            self.config_tester.run_common_tests()



       @unittest.skip(reason="""SwiftFormer does not use inputs_embeds"""    )
       def 					__lowercase						(							self    ) ->      Any:






            '''simple docstring'''





            pass



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






            '''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			:Any          =						model_class(_UpperCAmelCase    )
                 __snake_case			:Any          =						model.get_output_embeddings()
                 self.assertTrue(x is None or isinstance(_UpperCAmelCase			,						nn.Linear    )    )



       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





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

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

                 __snake_case			:Optional[Any]          =						["""pixel_values"""]
                 self.assertListEqual(arg_names[:1]			,						_UpperCAmelCase    )



       def 					__lowercase						(							self    ) ->      int:






            '''simple docstring'''





            __snake_case			:List[Any]          =						self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*_UpperCAmelCase    )



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






            '''simple docstring'''





            __snake_case			:Any          =						self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase    )



       @slow
       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





            for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 __snake_case			:Optional[int]          =						SwiftFormerModel.from_pretrained(_UpperCAmelCase    )
                 self.assertIsNotNone(_UpperCAmelCase    )



       @unittest.skip(reason="""SwiftFormer does not output attentions"""    )
       def 					__lowercase						(							self    ) ->      str:






            '''simple docstring'''





            pass



       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





            def check_hidden_states_output(a__			,						a__			,						a__    ):
                 __snake_case			:Tuple          =						model_class(_UpperCAmelCase    )
                 model.to(_UpperCAmelCase    )
                 model.eval()

                 with torch.no_grad():
                      __snake_case			:Dict          =						model(**self._prepare_for_class(_UpperCAmelCase			,						_UpperCAmelCase    )    )

                 __snake_case			:List[Any]          =						outputs.hidden_states

                 __snake_case			:int          =						8
                 self.assertEqual(len(_UpperCAmelCase    )			,						_UpperCAmelCase    )  # TODO

                 # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width)
                 # with the width and height being successively divided by 2, after every 2 blocks
                 for i in range(len(_UpperCAmelCase    )    ):
                      self.assertEqual(
                          hidden_states[i].shape			,						torch.Size(
                              [
                                  self.model_tester.batch_size,
                                  self.model_tester.embed_dims[i // 2],
                                  (self.model_tester.image_size // 4) // 2 ** (i // 2),
                                  (self.model_tester.image_size // 4) // 2 ** (i // 2),
                              ]    )			,						)

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

            for model_class in self.all_model_classes:
                 __snake_case			:List[Any]          =						True
                 check_hidden_states_output(_UpperCAmelCase			,						_UpperCAmelCase			,						_UpperCAmelCase    )

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

                 check_hidden_states_output(_UpperCAmelCase			,						_UpperCAmelCase			,						_UpperCAmelCase    )



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






            '''simple docstring'''





            def _config_zero_init(a__    ):
                 __snake_case			:Tuple          =						copy.deepcopy(_UpperCAmelCase    )
                 for key in configs_no_init.__dict__.keys():
                      if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key:
                           setattr(_UpperCAmelCase			,						_UpperCAmelCase			,						1e-10    )
                      if isinstance(getattr(_UpperCAmelCase			,						_UpperCAmelCase			,						_UpperCAmelCase    )			,						_UpperCAmelCase    ):
                           __snake_case			:Tuple          =						_config_zero_init(getattr(_UpperCAmelCase			,						_UpperCAmelCase    )    )
                           setattr(_UpperCAmelCase			,						_UpperCAmelCase			,						_UpperCAmelCase    )
                 return configs_no_init

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

            __snake_case			:Union[str, Any]          =						_config_zero_init(_UpperCAmelCase    )
            for model_class in self.all_model_classes:
                 __snake_case			:List[str]          =						model_class(config=_UpperCAmelCase    )
                 for name, param in model.named_parameters():
                      if param.requires_grad:
                           self.assertIn(
                               ((param.data.mean() * 1e9) / 1e9).round().item()			,						[0.0, 1.0]			,						msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''			,						)



       @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""    )
       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





            pass






def   UpperCamelCase  (       ):




     '''simple docstring'''






     __snake_case			:List[str]          =						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""  )
     return image







@require_torch
@require_vision
class 			snake_case__   (							unittest.TestCase):

       '''simple docstring'''



       @cached_property
       def 					__lowercase						(							self    ) ->      Optional[int]:






            '''simple docstring'''





            return ViTImageProcessor.from_pretrained("""MBZUAI/swiftformer-xs"""    ) if is_vision_available() else None



       @slow
       def 					__lowercase						(							self    ) ->      str:






            '''simple docstring'''





            __snake_case			:Union[str, Any]          =						SwiftFormerForImageClassification.from_pretrained("""MBZUAI/swiftformer-xs"""    ).to(_UpperCAmelCase    )

            __snake_case			:Optional[Any]          =						self.default_image_processor
            __snake_case			:List[str]          =						prepare_img()
            __snake_case			:List[str]          =						image_processor(images=_UpperCAmelCase			,						return_tensors="""pt"""    ).to(_UpperCAmelCase    )

            # forward pass
            with torch.no_grad():
                 __snake_case			:Optional[int]          =						model(**_UpperCAmelCase    )

            # verify the logits
            __snake_case			:Optional[Any]          =						torch.Size((1, 10_00)    )
            self.assertEqual(outputs.logits.shape			,						_UpperCAmelCase    )

            __snake_case			:Tuple          =						torch.tensor([[-2.17_03e00, 2.11_07e00, -2.08_11e00]]    ).to(_UpperCAmelCase    )
            self.assertTrue(torch.allclose(outputs.logits[0, :3]			,						_UpperCAmelCase			,						atol=1e-4    )    )










import math

lowerCamelCase__							=     10
lowerCamelCase__							=     7
lowerCamelCase__							=     BALLS_PER_COLOUR * NUM_COLOURS






def   UpperCamelCase  (       snake_case__     :   int = 20  ):




     '''simple docstring'''






     __snake_case			:Dict          =						math.comb(snake_case__	,snake_case__  )
     __snake_case			:int          =						math.comb(NUM_BALLS - BALLS_PER_COLOUR	,snake_case__  )

     __snake_case			:List[str]          =						NUM_COLOURS * (1 - missing_colour / total)

     return f'''{result:.9f}'''


if __name__ == "__main__":
     print(solution(20))


