





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    snake_case_				(		a_						):






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






   '''simple docstring'''

   __lowerCAmelCase     :       List[Any]						=   self.config_class(**self.inputs_dict			)
   self.parent.assertTrue(hasattr(_snake_case   ,  """hidden_sizes"""			)			)
   self.parent.assertTrue(hasattr(_snake_case   ,  """num_encoder_blocks"""			)			)






class    snake_case_				:






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






   '''simple docstring'''

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






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






   '''simple docstring'''

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

   __lowerCAmelCase     :       Tuple						=   None
   if self.use_labels:
    __lowerCAmelCase     :       Dict						=   ids_tensor([self.batch_size, self.image_size, self.image_size]   ,  self.num_labels			)

   __lowerCAmelCase     :       Union[str, Any]						=   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       UpperCAmelCase__						(							self :     Optional[int]   ,  _snake_case :     int   ,  _snake_case :     Union[str, Any]   ,  _snake_case :     str			)->str:






   '''simple docstring'''

   __lowerCAmelCase     :       Dict						=   PoolFormerModel(config=_snake_case			)
   model.to(_snake_case			)
   model.eval()
   __lowerCAmelCase     :       Optional[int]						=   model(_snake_case			)
   __lowerCAmelCase     :       str						=   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       UpperCAmelCase__						(							self :     Union[str, Any]			)->Dict:






   '''simple docstring'''

   __lowerCAmelCase     :       Dict						=   self.prepare_config_and_inputs()
   __lowerCAmelCase     :       Tuple						=   config_and_inputs
   __lowerCAmelCase     :       str						=   {'pixel_values': pixel_values}
   return config, inputs_dict






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

  A_										=    False
  A_										=    False
  A_										=    False
  A_										=    False
  A_										=    False






  def       UpperCAmelCase__						(							self :     Dict			)->Optional[int]:






   '''simple docstring'''

   __lowerCAmelCase     :       int						=   PoolFormerModelTester(self			)
   __lowerCAmelCase     :       List[Any]						=   PoolFormerConfigTester(self   ,  config_class=_snake_case			)






  def       UpperCAmelCase__						(							self :     Optional[Any]			)->int:






   '''simple docstring'''

   self.config_tester.run_common_tests()






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






   '''simple docstring'''

   __lowerCAmelCase     :       Optional[Any]						=   self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*_snake_case			)






  @unittest.skip("""PoolFormer does not use inputs_embeds"""			)
  def       UpperCAmelCase__						(							self :     List[Any]			)->Union[str, Any]:






   '''simple docstring'''

   pass






  @unittest.skip("""PoolFormer does not have get_input_embeddings method and get_output_embeddings methods"""			)
  def       UpperCAmelCase__						(							self :     List[Any]			)->List[Any]:






   '''simple docstring'''

   pass






  def       UpperCAmelCase__						(							self :     str			)->List[str]:






   '''simple docstring'''

   def check_hidden_states_output(_snake_case :     List[Any]   ,  _snake_case :     Dict   ,  _snake_case :     List[str]			):
    __lowerCAmelCase     :       Optional[int]						=   model_class(_snake_case			)
    model.to(_snake_case			)
    model.eval()

    with torch.no_grad():
     __lowerCAmelCase     :       Tuple						=   model(**self._prepare_for_class(_snake_case   ,  _snake_case			)			)

    __lowerCAmelCase     :       Tuple						=   outputs.hidden_states

    __lowerCAmelCase     :       Optional[int]						=   self.model_tester.num_encoder_blocks
    self.assertEqual(len(_snake_case			)   ,  _snake_case			)

    # 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,
        ]   ,  )

   __lowerCAmelCase     :       Optional[Any]						=   self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
    __lowerCAmelCase     :       Dict						=   True
    check_hidden_states_output(_snake_case   ,  _snake_case   ,  _snake_case			)

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

    check_hidden_states_output(_snake_case   ,  _snake_case   ,  _snake_case			)






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






   '''simple docstring'''

   if not self.model_tester.is_training:
    return

   __lowerCAmelCase     :       Union[str, Any]						=   self.model_tester.prepare_config_and_inputs_for_common()
   __lowerCAmelCase     :       Tuple						=   True

   for model_class in self.all_model_classes:
    if model_class in get_values(_snake_case			):
     continue
    __lowerCAmelCase     :       int						=   model_class(_snake_case			)
    model.to(_snake_case			)
    model.train()
    __lowerCAmelCase     :       List[Any]						=   self._prepare_for_class(_snake_case   ,  _snake_case   ,  return_labels=_snake_case			)
    __lowerCAmelCase     :       List[Any]						=   model(**_snake_case			).loss
    loss.backward()






  def       UpperCAmelCase__						(							self :     List[str]			)->List[str]:






   '''simple docstring'''

   __lowerCAmelCase     :       Optional[Any]						=   self.model_tester.prepare_config_and_inputs_for_common()

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

    __lowerCAmelCase     :       Any						=   ['pixel_values']
    self.assertListEqual(arg_names[:1]   ,  _snake_case			)






  @slow
  def       UpperCAmelCase__						(							self :     List[str]			)->str:






   '''simple docstring'''

   for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
    __lowerCAmelCase     :       Any						=   PoolFormerModel.from_pretrained(_snake_case			)
    self.assertIsNotNone(_snake_case			)






def        _SCREAMING_SNAKE_CASE		(			)			->    Any:
 __lowerCAmelCase     :       List[str]						=   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    )
 return image







@require_torch
class    snake_case_				(		unittest.TestCase						):






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






   '''simple docstring'''

   __lowerCAmelCase     :       int						=   PoolFormerImageProcessor()
   __lowerCAmelCase     :       Union[str, Any]						=   PoolFormerForImageClassification.from_pretrained("""sail/poolformer_s12"""			).to(_snake_case			)

   __lowerCAmelCase     :       List[Any]						=   image_processor(images=prepare_img()   ,  return_tensors="""pt"""			).to(_snake_case			)

   # forward pass
   with torch.no_grad():
    __lowerCAmelCase     :       str						=   model(**_snake_case			)

   # verify the logits
   __lowerCAmelCase     :       str						=   torch.Size((1, 1000)			)
   self.assertEqual(outputs.logits.shape   ,  _snake_case			)

   __lowerCAmelCase     :       Union[str, Any]						=   torch.tensor([-0.6_113, 0.1_685, -0.0_492]			).to(_snake_case			)
   self.assertTrue(torch.allclose(outputs.logits[0, :3]   ,  _snake_case   ,  atol=1E-4			)			)
from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


UpperCAmelCase							= {'''configuration_nat''': ['''NAT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''NatConfig''']}


try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 UpperCAmelCase							= [
     '''NAT_PRETRAINED_MODEL_ARCHIVE_LIST''',
     '''NatForImageClassification''',
     '''NatModel''',
     '''NatPreTrainedModel''',
     '''NatBackbone''',
 ]

if TYPE_CHECKING:
 from .configuration_nat import NAT_PRETRAINED_CONFIG_ARCHIVE_MAP, NatConfig

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_nat import (
      NAT_PRETRAINED_MODEL_ARCHIVE_LIST,
      NatBackbone,
      NatForImageClassification,
      NatModel,
      NatPreTrainedModel,
  )

else:
 import sys

 UpperCAmelCase							= _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)



