



"""simple docstring"""





import inspect
import unittest

from transformers import ViTHybridConfig
from transformers.testing_utils import require_accelerate, 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, _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 ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel
  from transformers.models.vit_hybrid.modeling_vit_hybrid import VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image
class  lowercase__  :







       '''simple docstring'''


       def __init__(				self     :    List[str]						,							_UpperCAmelCase     :    List[str]						,							_UpperCAmelCase     :    int=13						,							_UpperCAmelCase     :    List[str]=64						,							_UpperCAmelCase     :    str=2						,							_UpperCAmelCase     :    Dict=3						,							_UpperCAmelCase     :    str=True						,							_UpperCAmelCase     :    Tuple=True						,							_UpperCAmelCase     :    Optional[int]=32						,							_UpperCAmelCase     :    str=5						,							_UpperCAmelCase     :    Any=4						,							_UpperCAmelCase     :    str=37						,							_UpperCAmelCase     :    Dict="gelu"						,							_UpperCAmelCase     :    Any=0.1						,							_UpperCAmelCase     :    Optional[int]=0.1						,							_UpperCAmelCase     :    Tuple=10						,							_UpperCAmelCase     :    List[Any]=0.02						,							_UpperCAmelCase     :    str=[1, 16, 4, 4]						,							_UpperCAmelCase     :    List[str]=None						,							)					->		Union[str, Any]:


             '''simple docstring'''




             UpperCAmelCase_     					=				parent
             UpperCAmelCase_     					=				batch_size
             UpperCAmelCase_     					=				image_size
             UpperCAmelCase_     					=				patch_size
             UpperCAmelCase_     					=				num_channels
             UpperCAmelCase_     					=				is_training
             UpperCAmelCase_     					=				use_labels
             UpperCAmelCase_     					=				hidden_size
             UpperCAmelCase_     					=				num_hidden_layers
             UpperCAmelCase_     					=				num_attention_heads
             UpperCAmelCase_     					=				intermediate_size
             UpperCAmelCase_     					=				hidden_act
             UpperCAmelCase_     					=				hidden_dropout_prob
             UpperCAmelCase_     					=				attention_probs_dropout_prob
             UpperCAmelCase_     					=				type_sequence_label_size
             UpperCAmelCase_     					=				initializer_range
             UpperCAmelCase_     					=				scope
             UpperCAmelCase_     					=				backbone_featmap_shape

             # in ViT hybrid, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
             # the number of patches is based on the feature map of the backbone, which by default uses an output stride
             # of 32, which means that the feature map has a spatial resolution of 1/32 of the input image size
             UpperCAmelCase_     					=				(self.image_size // 32) ** 2
             UpperCAmelCase_     					=				num_patches + 1



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


             '''simple docstring'''




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

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

             UpperCAmelCase_     					=				self.get_config()

             return config, pixel_values, labels



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


             '''simple docstring'''




             UpperCAmelCase_     					=				{
                 "global_padding": "same",
                 "layer_type": "bottleneck",
                 "depths": [3, 4, 9],
                 "out_features": ["stage1", "stage2", "stage3"],
                 "embedding_dynamic_padding": True,
                 "hidden_sizes": [4, 8, 16, 32],
                 "num_groups": 2,
             }

             return ViTHybridConfig(
                 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=_UpperCAmelCase						,							initializer_range=self.initializer_range						,							backbone_featmap_shape=self.backbone_featmap_shape						,							backbone_config=_UpperCAmelCase						,							)



       def 	lowercase__							(				self     :    List[str]						,							_UpperCAmelCase     :    Optional[Any]						,							_UpperCAmelCase     :    Dict						,							_UpperCAmelCase     :    Union[str, Any]       )					->		Optional[Any]:


             '''simple docstring'''




             UpperCAmelCase_     					=				ViTHybridModel(config=_UpperCAmelCase       )
             model.to(_UpperCAmelCase       )
             model.eval()
             UpperCAmelCase_     					=				model(_UpperCAmelCase       )
             self.parent.assertEqual(result.last_hidden_state.shape						,							(self.batch_size, self.seq_length, self.hidden_size)       )



       def 	lowercase__							(				self     :    Tuple						,							_UpperCAmelCase     :    Any						,							_UpperCAmelCase     :    List[str]						,							_UpperCAmelCase     :    Any       )					->		Optional[int]:


             '''simple docstring'''




             UpperCAmelCase_     					=				self.type_sequence_label_size
             UpperCAmelCase_     					=				ViTHybridForImageClassification(_UpperCAmelCase       )
             model.to(_UpperCAmelCase       )
             model.eval()
             UpperCAmelCase_     					=				model(_UpperCAmelCase						,							labels=_UpperCAmelCase       )
             self.parent.assertEqual(result.logits.shape						,							(self.batch_size, self.type_sequence_label_size)       )







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


             '''simple docstring'''




             UpperCAmelCase_     					=				self.prepare_config_and_inputs()
             UpperCAmelCase_					,       UpperCAmelCase_					,       UpperCAmelCase_     					=				config_and_inputs
             UpperCAmelCase_     					=				{"pixel_values": pixel_values}
             return config, inputs_dict



@require_torch
class  lowercase__  (       SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE							,   unittest.TestCase ):







       '''simple docstring'''


       UpperCamelCase		=	(ViTHybridModel, ViTHybridForImageClassification) if is_torch_available() else ()
       UpperCamelCase		=	(
           {'''feature-extraction''': ViTHybridModel, '''image-classification''': ViTHybridForImageClassification}
           if is_torch_available()
           else {}
       )
       UpperCamelCase		=	False
       UpperCamelCase		=	False
       UpperCamelCase		=	False



       def 	lowercase__							(				self     :    Dict       )					->		List[Any]:


             '''simple docstring'''




             UpperCAmelCase_     					=				ViTHybridModelTester(self       )
             UpperCAmelCase_     					=				ConfigTester(self						,							config_class=_UpperCAmelCase						,							has_text_modality=_UpperCAmelCase						,							hidden_size=37       )



       def 	lowercase__							(				self     :    List[Any]       )					->		Any:


             '''simple docstring'''




             self.config_tester.run_common_tests()



       @unittest.skip(reason="ViT does not use inputs_embeds"       )
       def 	lowercase__							(				self     :    Optional[Any]       )					->		List[Any]:


             '''simple docstring'''




             pass



       def 	lowercase__							(				self     :    Dict       )					->		Tuple:


             '''simple docstring'''




             UpperCAmelCase_					,       UpperCAmelCase_     					=				self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   UpperCAmelCase_     					=				model_class(_UpperCAmelCase       )
                   self.assertIsInstance(model.get_input_embeddings()						,							(nn.Module)       )
                   UpperCAmelCase_     					=				model.get_output_embeddings()
                   self.assertTrue(x is None or isinstance(_UpperCAmelCase						,							nn.Linear       )       )



       def 	lowercase__							(				self     :    Dict       )					->		Tuple:


             '''simple docstring'''




             UpperCAmelCase_					,       UpperCAmelCase_     					=				self.model_tester.prepare_config_and_inputs_for_common()

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

                   UpperCAmelCase_     					=				["pixel_values"]
                   self.assertListEqual(arg_names[:1]						,							_UpperCAmelCase       )



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


             '''simple docstring'''




             UpperCAmelCase_     					=				self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*_UpperCAmelCase       )



       def 	lowercase__							(				self     :    Any       )					->		List[Any]:


             '''simple docstring'''




             UpperCAmelCase_     					=				self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase       )



       def 	lowercase__							(				self     :    str       )					->		Any:


             '''simple docstring'''




             UpperCAmelCase_					,       UpperCAmelCase_     					=				self.model_tester.prepare_config_and_inputs_for_common()

             UpperCAmelCase_     					=				_config_zero_init(_UpperCAmelCase       )
             for model_class in self.all_model_classes:
                   UpperCAmelCase_     					=				model_class(config=_UpperCAmelCase       )
                   # Skip the check for the backbone
                   for name, module in model.named_modules():
                         if module.__class__.__name__ == "ViTHybridPatchEmbeddings":
                               UpperCAmelCase_     					=				[F"""{name}.{key}""" for key in module.state_dict().keys()]
                               break

                   for name, param in model.named_parameters():
                         if param.requires_grad:
                               if name in backbone_params:
                                     continue
                               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"""						,							)







       @slow
       def 	lowercase__							(				self     :    int       )					->		Optional[int]:


             '''simple docstring'''




             for model_name in VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   UpperCAmelCase_     					=				ViTHybridModel.from_pretrained(_UpperCAmelCase       )
                   self.assertIsNotNone(_UpperCAmelCase       )



def   a__      ( ):
      UpperCAmelCase_     					=				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
      return image


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







       '''simple docstring'''


       @cached_property
       def 	lowercase__							(				self     :    Tuple       )					->		Dict:


             '''simple docstring'''




             return (
                 ViTHybridImageProcessor.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )
                 if is_vision_available()
                 else None
             )



       @slow
       def 	lowercase__							(				self     :    str       )					->		Optional[Any]:


             '''simple docstring'''




             UpperCAmelCase_     					=				ViTHybridForImageClassification.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]       ).to(
                 _UpperCAmelCase       )

             UpperCAmelCase_     					=				self.default_image_processor
             UpperCAmelCase_     					=				prepare_img()
             UpperCAmelCase_     					=				image_processor(images=_UpperCAmelCase						,							return_tensors="pt"       ).to(_UpperCAmelCase       )

             # forward pass
             with torch.no_grad():
                   UpperCAmelCase_     					=				model(**_UpperCAmelCase       )

             # verify the logits
             UpperCAmelCase_     					=				torch.Size((1, 1000)       )
             self.assertEqual(outputs.logits.shape						,							_UpperCAmelCase       )

             UpperCAmelCase_     					=				torch.tensor([-1.9090, -0.4993, -0.2389]       ).to(_UpperCAmelCase       )

             self.assertTrue(torch.allclose(outputs.logits[0, :3]						,							_UpperCAmelCase						,							atol=1e-4       )       )







       @slow
       @require_accelerate
       def 	lowercase__							(				self     :    Union[str, Any]       )					->		List[str]:


             '''simple docstring'''




             UpperCAmelCase_     					=				ViTHybridImageProcessor.from_pretrained("google/vit-hybrid-base-bit-384"       )
             UpperCAmelCase_     					=				ViTHybridForImageClassification.from_pretrained("google/vit-hybrid-base-bit-384"						,							device_map="auto"       )

             UpperCAmelCase_     					=				prepare_img()

             UpperCAmelCase_     					=				image_processor(images=_UpperCAmelCase						,							return_tensors="pt"       )
             UpperCAmelCase_     					=				model(**_UpperCAmelCase       )
             UpperCAmelCase_     					=				outputs.logits
             # model predicts one of the 1000 ImageNet classes
             UpperCAmelCase_     					=				logits.argmax(-1       ).item()

             self.assertTrue(model.config.idalabel[predicted_class_idx]						,							"tabby, tabby cat"       )








def     __SCREAMING_SNAKE_CASE							(       )		->     Optional[int]:




						'''simple docstring'''







						__UpperCAmelCase			:							str	    =	[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

						__UpperCAmelCase			:							Union[str, Any]	    =	6
						__UpperCAmelCase			:							Optional[Any]	    =	1
						__UpperCAmelCase			:							Tuple	    =	1901

						__UpperCAmelCase			:							Any	    =	0

						while year < 2001:
												day += 7

												if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
																		if day > days_per_month[month - 1] and month != 2:
																								month += 1
																								__UpperCAmelCase			:							Optional[int]	    =	day - days_per_month[month - 2]
																		elif day > 29 and month == 2:
																								month += 1
																								__UpperCAmelCase			:							Optional[Any]	    =	day - 29
												else:
																		if day > days_per_month[month - 1]:
																								month += 1
																								__UpperCAmelCase			:							Optional[Any]	    =	day - days_per_month[month - 2]

												if month > 12:
																		year += 1
																		__UpperCAmelCase			:							int	    =	1

												if year < 2001 and day == 1:
																		sundays += 1
						return sundays


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

