

"""simple docstring"""




import inspect
import unittest

from transformers import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

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 transformers import MODEL_MAPPING, PoolFormerConfig, PoolFormerForImageClassification, PoolFormerModel
      from transformers.models.poolformer.modeling_poolformer import POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import PoolFormerImageProcessor







class    __lowercase	(			__a    ):

  def       __lowercase				(     self						:	Optional[int]			):






   '''simple docstring'''
   UpperCAmelCase__    :     Dict          =    self.config_class(**self.inputs_dict			)
   self.parent.assertTrue(hasattr(lowerCAmelCase__    ,"""hidden_sizes"""			)			)
   self.parent.assertTrue(hasattr(lowerCAmelCase__    ,"""num_encoder_blocks"""			)			)







class    __lowercase	:

  def __init__(     self						:	Optional[int]    ,A						:	str    ,A						:	List[Any]=13    ,A						:	Dict=64    ,A						:	Union[str, Any]=3    ,A						:	Tuple=4    ,A						:	str=[2, 2, 2, 2]    ,A						:	str=[8, 4, 2, 1]    ,A						:	str=[16, 32, 64, 128]    ,A						:	Optional[int]=[1, 4, 8, 16]    ,A						:	int=False    ,A						:	Optional[Any]=True    ,A						:	int="gelu"    ,A						:	Dict=0.1    ,A						:	Dict=0.0_2    ,A						:	Optional[int]=3    ,A						:	List[str]=None    ,):






   '''simple docstring'''
   UpperCAmelCase__    :     List[str]          =    parent
   UpperCAmelCase__    :     Any          =    batch_size
   UpperCAmelCase__    :     Dict          =    image_size
   UpperCAmelCase__    :     Dict          =    num_channels
   UpperCAmelCase__    :     str          =    num_encoder_blocks
   UpperCAmelCase__    :     Any          =    sr_ratios
   UpperCAmelCase__    :     Any          =    depths
   UpperCAmelCase__    :     List[str]          =    hidden_sizes
   UpperCAmelCase__    :     int          =    downsampling_rates
   UpperCAmelCase__    :     str          =    is_training
   UpperCAmelCase__    :     str          =    use_labels
   UpperCAmelCase__    :     Any          =    hidden_act
   UpperCAmelCase__    :     List[Any]          =    hidden_dropout_prob
   UpperCAmelCase__    :     List[Any]          =    initializer_range
   UpperCAmelCase__    :     Any          =    num_labels
   UpperCAmelCase__    :     Any          =    scope

  def       __lowercase				(     self						:	Dict			):






   '''simple docstring'''
   UpperCAmelCase__    :     Dict          =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

   UpperCAmelCase__    :     Dict          =    None
   if self.use_labels:
    UpperCAmelCase__    :     List[str]          =    ids_tensor([self.batch_size, self.image_size, self.image_size]    ,self.num_labels			)

   UpperCAmelCase__    :     Dict          =    PoolFormerConfig(
       image_size=self.image_size    ,num_channels=self.num_channels    ,num_encoder_blocks=self.num_encoder_blocks    ,depths=self.depths    ,hidden_sizes=self.hidden_sizes    ,hidden_act=self.hidden_act    ,hidden_dropout_prob=self.hidden_dropout_prob    ,initializer_range=self.initializer_range    ,)

   return config, pixel_values, labels

  def       __lowercase				(     self						:	Union[str, Any]    ,A						:	Union[str, Any]    ,A						:	Optional[int]    ,A						:	Optional[Any]			):






   '''simple docstring'''
   UpperCAmelCase__    :     Dict          =    PoolFormerModel(config=lowerCAmelCase__			)
   model.to(lowerCAmelCase__			)
   model.eval()
   UpperCAmelCase__    :     str          =    model(lowerCAmelCase__			)
   UpperCAmelCase__    :     Tuple          =    self.image_size // 32.0
   self.parent.assertEqual(
       result.last_hidden_state.shape    ,(self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)			)




  def       __lowercase				(     self						:	Dict			):






   '''simple docstring'''
   UpperCAmelCase__    :     Optional[int]          =    self.prepare_config_and_inputs()
   UpperCAmelCase__    :     str          =    config_and_inputs
   UpperCAmelCase__    :     List[Any]          =    {"""pixel_values""": pixel_values}
   return config, inputs_dict







@require_torch
class    __lowercase	(			__a		,	__a		,	unittest.TestCase    ):
  snake_case_ 				=				(PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
  snake_case_ 				=				(
      {"""feature-extraction""": PoolFormerModel, """image-classification""": PoolFormerForImageClassification}
      if is_torch_available()
      else {}
  )

  snake_case_ 				=				False
  snake_case_ 				=				False
  snake_case_ 				=				False
  snake_case_ 				=				False
  snake_case_ 				=				False

  def       __lowercase				(     self						:	Dict			):






   '''simple docstring'''
   UpperCAmelCase__    :     int          =    PoolFormerModelTester(self			)
   UpperCAmelCase__    :     Optional[int]          =    PoolFormerConfigTester(self    ,config_class=lowerCAmelCase__			)

  def       __lowercase				(     self						:	str			):






   '''simple docstring'''
   self.config_tester.run_common_tests()

  def       __lowercase				(     self						:	Any			):






   '''simple docstring'''
   UpperCAmelCase__    :     str          =    self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*lowerCAmelCase__			)

  @unittest.skip("""PoolFormer does not use inputs_embeds"""			)
  def       __lowercase				(     self						:	Tuple			):






   '''simple docstring'''
   pass

  @unittest.skip("""PoolFormer does not have get_input_embeddings method and get_output_embeddings methods"""			)
  def       __lowercase				(     self						:	Tuple			):






   '''simple docstring'''
   pass

  def       __lowercase				(     self						:	Dict			):






   '''simple docstring'''
   def check_hidden_states_output(A						:	Optional[Any]    ,A						:	int    ,A						:	Dict			):
    UpperCAmelCase__    :     Dict          =    model_class(lowerCAmelCase__			)
    model.to(lowerCAmelCase__			)
    model.eval()

    with torch.no_grad():
     UpperCAmelCase__    :     Any          =    model(**self._prepare_for_class(lowerCAmelCase__    ,lowerCAmelCase__			)			)

    UpperCAmelCase__    :     List[str]          =    outputs.hidden_states

    UpperCAmelCase__    :     Optional[Any]          =    self.model_tester.num_encoder_blocks
    self.assertEqual(len(lowerCAmelCase__			)    ,lowerCAmelCase__			)

    # verify the first hidden states (first block)
    self.assertListEqual(
        list(hidden_states[0].shape[-3:]			)    ,[
            self.model_tester.hidden_sizes[0],
            self.model_tester.image_size // 4,
            self.model_tester.image_size // 4,
        ]    ,)

   UpperCAmelCase__    :     Any          =    self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
    UpperCAmelCase__    :     Any          =    True
    check_hidden_states_output(lowerCAmelCase__    ,lowerCAmelCase__    ,lowerCAmelCase__			)

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

    check_hidden_states_output(lowerCAmelCase__    ,lowerCAmelCase__    ,lowerCAmelCase__			)

  def       __lowercase				(     self						:	Any			):






   '''simple docstring'''
   if not self.model_tester.is_training:
    return

   UpperCAmelCase__    :     Optional[Any]          =    self.model_tester.prepare_config_and_inputs_for_common()
   UpperCAmelCase__    :     str          =    True

   for model_class in self.all_model_classes:
    if model_class in get_values(lowerCAmelCase__			):
     continue
    UpperCAmelCase__    :     Union[str, Any]          =    model_class(lowerCAmelCase__			)
    model.to(lowerCAmelCase__			)
    model.train()
    UpperCAmelCase__    :     Optional[Any]          =    self._prepare_for_class(lowerCAmelCase__    ,lowerCAmelCase__    ,return_labels=lowerCAmelCase__			)
    UpperCAmelCase__    :     List[Any]          =    model(**lowerCAmelCase__			).loss
    loss.backward()

  def       __lowercase				(     self						:	Optional[int]			):






   '''simple docstring'''
   UpperCAmelCase__    :     str          =    self.model_tester.prepare_config_and_inputs_for_common()

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

    UpperCAmelCase__    :     Any          =    ["""pixel_values"""]
    self.assertListEqual(arg_names[:1]    ,lowerCAmelCase__			)




  @slow
  def       __lowercase				(     self						:	str			):






   '''simple docstring'''
   for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
    UpperCAmelCase__    :     List[str]          =    PoolFormerModel.from_pretrained(lowerCAmelCase__			)
    self.assertIsNotNone(lowerCAmelCase__			)







def      lowerCAmelCase  (    ):
 '''simple docstring'''





 UpperCAmelCase__    :     Optional[int]          =    Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""					)
 return image







@require_torch
class    __lowercase	(			unittest.TestCase    ):

  @slow
  def       __lowercase				(     self						:	Optional[int]			):






   '''simple docstring'''
   UpperCAmelCase__    :     Dict          =    PoolFormerImageProcessor()
   UpperCAmelCase__    :     Any          =    PoolFormerForImageClassification.from_pretrained("""sail/poolformer_s12"""			).to(lowerCAmelCase__			)

   UpperCAmelCase__    :     int          =    image_processor(images=prepare_img()    ,return_tensors="""pt"""			).to(lowerCAmelCase__			)

   # forward pass
   with torch.no_grad():
    UpperCAmelCase__    :     Optional[Any]          =    model(**lowerCAmelCase__			)

   # verify the logits
   UpperCAmelCase__    :     int          =    torch.Size((1, 1_000)			)
   self.assertEqual(outputs.logits.shape    ,lowerCAmelCase__			)

   UpperCAmelCase__    :     Any          =    torch.tensor([-0.6_1_1_3, 0.1_6_8_5, -0.0_4_9_2]			).to(lowerCAmelCase__			)
   self.assertTrue(torch.allclose(outputs.logits[0, :3]    ,lowerCAmelCase__    ,atol=1e-4			)			)







'''simple docstring'''

from itertools import combinations, product







def __A  (    lowerCAmelCase_ ,       lowerCAmelCase_ ,       lowerCAmelCase_ ,       lowerCAmelCase_       ):
     if xa == ya == 0 or xa == ya == 0:
          return False
     _UpperCAmelCase					:  Any         =    xa * xa + ya * ya
     _UpperCAmelCase					:  Any         =    xa * xa + ya * ya
     _UpperCAmelCase					:  Tuple         =    (xa - xa) * (xa - xa) + (ya - ya) * (ya - ya)
     return (
         a_square + b_square == c_square
         or a_square + c_square == b_square
         or b_square + c_square == a_square
     )







def __A  (    lowerCAmelCase_ = 50       ):
     return sum(
         1
         for pta, pta in combinations(product(range(limit + 1       ) ,       repeat=2       ) ,       2       )
         if is_right(*lowerCAmelCase_ ,       *lowerCAmelCase_       )       )


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


