"""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      __SCREAMING_SNAKE_CASE    :







  '''simple docstring'''


  def __init__(		self   :       Optional[int]					,   __a   :       str					,   __a   :       str=13					,   __a   :       Any=64					,   __a   :       List[str]=2					,   __a   :       Dict=3					,   __a   :       List[Any]=True					,   __a   :       Optional[Any]=True					,   __a   :       Optional[int]=32					,   __a   :       List[str]=5					,   __a   :       int=4					,   __a   :       Dict=37					,   __a   :       List[Any]="gelu"					,   __a   :       Any=0.1					,   __a   :       Optional[Any]=0.1					,   __a   :       int=10					,   __a   :       Optional[int]=0.02					,   __a   :       Dict=[1, 16, 4, 4]					,   __a   :       Optional[int]=None					,   )		->				str:
        _UpperCamelCase      :	str						=       parent
        _UpperCamelCase      :	Optional[Any]						=       batch_size
        _UpperCamelCase      :	List[str]						=       image_size
        _UpperCamelCase      :	Optional[int]						=       patch_size
        _UpperCamelCase      :	Union[str, Any]						=       num_channels
        _UpperCamelCase      :	Optional[int]						=       is_training
        _UpperCamelCase      :	List[Any]						=       use_labels
        _UpperCamelCase      :	Dict						=       hidden_size
        _UpperCamelCase      :	List[str]						=       num_hidden_layers
        _UpperCamelCase      :	Optional[int]						=       num_attention_heads
        _UpperCamelCase      :	Union[str, Any]						=       intermediate_size
        _UpperCamelCase      :	Optional[int]						=       hidden_act
        _UpperCamelCase      :	Tuple						=       hidden_dropout_prob
        _UpperCamelCase      :	Dict						=       attention_probs_dropout_prob
        _UpperCamelCase      :	Optional[Any]						=       type_sequence_label_size
        _UpperCamelCase      :	Optional[int]						=       initializer_range
        _UpperCamelCase      :	Optional[Any]						=       scope
        _UpperCamelCase      :	int						=       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      :	Dict						=       (self.image_size // 32) ** 2
        _UpperCamelCase      :	str						=       num_patches + 1

  def    __SCREAMING_SNAKE_CASE				(		self   :       Union[str, Any]	)		->				Tuple:
        _UpperCamelCase      :	Union[str, Any]						=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

        _UpperCamelCase      :	List[str]						=       None
        if self.use_labels:
              _UpperCamelCase      :	Dict						=       ids_tensor([self.batch_size]					,   self.type_sequence_label_size	)

        _UpperCamelCase      :	Any						=       self.get_config()

        return config, pixel_values, labels

  def    __SCREAMING_SNAKE_CASE				(		self   :       int	)		->				Any:
        _UpperCamelCase      :	Dict						=       {
            "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    __SCREAMING_SNAKE_CASE				(		self   :       int					,   __a   :       List[Any]					,   __a   :       List[Any]					,   __a   :       Union[str, Any]	)		->				int:
        _UpperCamelCase      :	Any						=       ViTHybridModel(config=__UpperCamelCase	)
        model.to(__UpperCamelCase	)
        model.eval()
        _UpperCamelCase      :	Optional[Any]						=       model(__UpperCamelCase	)
        self.parent.assertEqual(result.last_hidden_state.shape					,   (self.batch_size, self.seq_length, self.hidden_size)	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Any					,   __a   :       str					,   __a   :       int					,   __a   :       Dict	)		->				Dict:
        _UpperCamelCase      :	Optional[Any]						=       self.type_sequence_label_size
        _UpperCamelCase      :	Tuple						=       ViTHybridForImageClassification(__UpperCamelCase	)
        model.to(__UpperCamelCase	)
        model.eval()
        _UpperCamelCase      :	List[Any]						=       model(__UpperCamelCase					,   labels=__UpperCamelCase	)
        self.parent.assertEqual(result.logits.shape					,   (self.batch_size, self.type_sequence_label_size)	)


  def    __SCREAMING_SNAKE_CASE				(		self   :       int	)		->				Optional[int]:
        _UpperCamelCase      :	str						=       self.prepare_config_and_inputs()
        _UpperCamelCase,  _UpperCamelCase,  _UpperCamelCase      :	Union[str, Any]						=       config_and_inputs
        _UpperCamelCase      :	Optional[int]						=       {"pixel_values": pixel_values}
        return config, inputs_dict





@require_torch
class      __SCREAMING_SNAKE_CASE    (						_UpperCamelCase		,  _UpperCamelCase		,  unittest.TestCase   ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__							:Optional[Any]	     =					(ViTHybridModel, ViTHybridForImageClassification) if is_torch_available() else ()
  SCREAMING_SNAKE_CASE__							:Tuple	     =					(
      {"feature-extraction": ViTHybridModel, "image-classification": ViTHybridForImageClassification}
      if is_torch_available()
      else {}
  )
  SCREAMING_SNAKE_CASE__							:List[str]	     =					False
  SCREAMING_SNAKE_CASE__							:int	     =					False
  SCREAMING_SNAKE_CASE__							:Union[str, Any]	     =					False

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]	)		->				Tuple:
        _UpperCamelCase      :	int						=       ViTHybridModelTester(self	)
        _UpperCamelCase      :	Optional[Any]						=       ConfigTester(self					,   config_class=__UpperCamelCase					,   has_text_modality=__UpperCamelCase					,   hidden_size=37	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				Optional[Any]:
        self.config_tester.run_common_tests()

  @unittest.skip(reason="ViT does not use inputs_embeds"	)
  def    __SCREAMING_SNAKE_CASE				(		self   :       Any	)		->				Any:
        pass

  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				List[Any]:
        _UpperCamelCase,  _UpperCamelCase      :	Any						=       self.model_tester.prepare_config_and_inputs_for_common()

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

  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]	)		->				Optional[int]:
        _UpperCamelCase,  _UpperCamelCase      :	Union[str, Any]						=       self.model_tester.prepare_config_and_inputs_for_common()

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

              _UpperCamelCase      :	int						=       ["pixel_values"]
              self.assertListEqual(arg_names[:1]					,   __UpperCamelCase	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       int	)		->				List[str]:
        _UpperCamelCase      :	str						=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__UpperCamelCase	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Any	)		->				Dict:
        _UpperCamelCase      :	Union[str, Any]						=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       str	)		->				int:
        _UpperCamelCase,  _UpperCamelCase      :	Dict						=       self.model_tester.prepare_config_and_inputs_for_common()

        _UpperCamelCase      :	Dict						=       _config_zero_init(__UpperCamelCase	)
        for model_class in self.all_model_classes:
              _UpperCamelCase      :	str						=       model_class(config=__UpperCamelCase	)
              # Skip the check for the backbone
              for name, module in model.named_modules():
                    if module.__class__.__name__ == "ViTHybridPatchEmbeddings":
                          _UpperCamelCase      :	Optional[int]						=       [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    __SCREAMING_SNAKE_CASE				(		self   :       List[str]	)		->				Tuple:
        for model_name in VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              _UpperCamelCase      :	Any						=       ViTHybridModel.from_pretrained(__UpperCamelCase	)
              self.assertIsNotNone(__UpperCamelCase	)





def 					lowercase__    (					)					->		Tuple:




      """simple docstring"""

      _UpperCamelCase      :	Any						=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"			)
      return image



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







  '''simple docstring'''


  @cached_property
  def    __SCREAMING_SNAKE_CASE				(		self   :       Dict	)		->				Optional[Any]:
        return (
            ViTHybridImageProcessor.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)
            if is_vision_available()
            else None
        )

  @slow
  def    __SCREAMING_SNAKE_CASE				(		self   :       int	)		->				Dict:
        _UpperCamelCase      :	Any						=       ViTHybridForImageClassification.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]	).to(
            __UpperCamelCase	)

        _UpperCamelCase      :	Dict						=       self.default_image_processor
        _UpperCamelCase      :	Optional[int]						=       prepare_img()
        _UpperCamelCase      :	int						=       image_processor(images=__UpperCamelCase					,   return_tensors="pt"	).to(__UpperCamelCase	)

        # forward pass
        with torch.no_grad():
              _UpperCamelCase      :	Union[str, Any]						=       model(**__UpperCamelCase	)

        # verify the logits
        _UpperCamelCase      :	Optional[int]						=       torch.Size((1, 1000)	)
        self.assertEqual(outputs.logits.shape					,   __UpperCamelCase	)

        _UpperCamelCase      :	str						=       torch.tensor([-1.90_90, -0.49_93, -0.23_89]	).to(__UpperCamelCase	)

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


  @slow
  @require_accelerate
  def    __SCREAMING_SNAKE_CASE				(		self   :       str	)		->				List[str]:
        _UpperCamelCase      :	int						=       ViTHybridImageProcessor.from_pretrained("google/vit-hybrid-base-bit-384"	)
        _UpperCamelCase      :	List[Any]						=       ViTHybridForImageClassification.from_pretrained("google/vit-hybrid-base-bit-384"					,   device_map="auto"	)

        _UpperCamelCase      :	List[Any]						=       prepare_img()

        _UpperCamelCase      :	Tuple						=       image_processor(images=__UpperCamelCase					,   return_tensors="pt"	)
        _UpperCamelCase      :	Dict						=       model(**__UpperCamelCase	)
        _UpperCamelCase      :	Union[str, Any]						=       outputs.logits
        # model predicts one of the 1000 ImageNet classes
        _UpperCamelCase      :	Union[str, Any]						=       logits.argmax(-1	).item()

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







"""simple docstring"""


from collections import defaultdict
from math import ceil, sqrt




def 					lowercase__    (					lowercase_ = 1_000_000		,lowercase_ = 10			)					->		int:




      """simple docstring"""

      _UpperCamelCase      :	defaultdict						=       defaultdict(lowercase_			)

      for outer_width in range(3		,(t_limit // 4) + 2			):
            if outer_width * outer_width > t_limit:
                  _UpperCamelCase      :	Any						=       max(
                      ceil(sqrt(outer_width * outer_width - t_limit			)			)		,1			)
            else:
                  _UpperCamelCase      :	str						=       1

            hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2

            for hole_width in range(lowercase_		,outer_width - 1		,2			):
                  count[outer_width * outer_width - hole_width * hole_width] += 1

      return sum(1 for n in count.values() if 1 <= n <= 10			)


if __name__ == "__main__":
  print(f"""{solution() = }""")
