




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     a  (     _A    ):

     '''simple docstring'''





     def 						lowerCamelCase_     (			self     :    Any       ):
         UpperCAmelCase_											=  self.config_class(**self.inputs_dict       )
         self.parent.assertTrue(hasattr(__snake_case      ,					'''hidden_sizes'''       )       )
         self.parent.assertTrue(hasattr(__snake_case      ,					'''num_encoder_blocks'''       )       )



class     a  :

     '''simple docstring'''





     def __init__(			self     :    Union[str, Any]      ,					__snake_case     :    Dict      ,					__snake_case     :    str=13      ,					__snake_case     :    str=64      ,					__snake_case     :    Any=3      ,					__snake_case     :    Any=4      ,					__snake_case     :    List[Any]=[2, 2, 2, 2]      ,					__snake_case     :    Any=[8, 4, 2, 1]      ,					__snake_case     :    List[Any]=[16, 32, 64, 1_28]      ,					__snake_case     :    Tuple=[1, 4, 8, 16]      ,					__snake_case     :    Tuple=False      ,					__snake_case     :    Optional[Any]=True      ,					__snake_case     :    str="gelu"      ,					__snake_case     :    List[Any]=0.1      ,					__snake_case     :    Optional[Any]=0.02      ,					__snake_case     :    Union[str, Any]=3      ,					__snake_case     :    Any=None      ,					):
         UpperCAmelCase_											=  parent
         UpperCAmelCase_											=  batch_size
         UpperCAmelCase_											=  image_size
         UpperCAmelCase_											=  num_channels
         UpperCAmelCase_											=  num_encoder_blocks
         UpperCAmelCase_											=  sr_ratios
         UpperCAmelCase_											=  depths
         UpperCAmelCase_											=  hidden_sizes
         UpperCAmelCase_											=  downsampling_rates
         UpperCAmelCase_											=  is_training
         UpperCAmelCase_											=  use_labels
         UpperCAmelCase_											=  hidden_act
         UpperCAmelCase_											=  hidden_dropout_prob
         UpperCAmelCase_											=  initializer_range
         UpperCAmelCase_											=  num_labels
         UpperCAmelCase_											=  scope
     def 						lowerCamelCase_     (			self     :    Tuple       ):
         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.image_size, self.image_size]      ,					self.num_labels       )

         UpperCAmelCase_											=  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 						lowerCamelCase_     (			self     :    Union[str, Any]      ,					__snake_case     :    Union[str, Any]      ,					__snake_case     :    Any      ,					__snake_case     :    Dict       ):
         UpperCAmelCase_											=  PoolFormerModel(config=__snake_case       )
         model.to(__snake_case       )
         model.eval()
         UpperCAmelCase_											=  model(__snake_case       )
         UpperCAmelCase_											=  UpperCAmelCase_											=  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 						lowerCamelCase_     (			self     :    Any       ):
         UpperCAmelCase_											=  self.prepare_config_and_inputs()
         UpperCAmelCase_				,							UpperCAmelCase_				,							UpperCAmelCase_											=  config_and_inputs
         UpperCAmelCase_											=  {'''pixel_values''': pixel_values}
         return config, inputs_dict



@require_torch
class     a  (     _A			,     _A			,     unittest.TestCase    ):

     '''simple docstring'''





     lowerCAmelCase       : int     	=						(PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
     lowerCAmelCase       : Optional[int]     	=						(
         {'feature-extraction': PoolFormerModel, 'image-classification': PoolFormerForImageClassification}
         if is_torch_available()
         else {}
     )

     lowerCAmelCase       : Dict     	=						False
     lowerCAmelCase       : Any     	=						False
     lowerCAmelCase       : Optional[Any]     	=						False
     lowerCAmelCase       : Any     	=						False
     lowerCAmelCase       : Any     	=						False
     def 						lowerCamelCase_     (			self     :    List[str]       ):
         UpperCAmelCase_											=  PoolFormerModelTester(self       )
         UpperCAmelCase_											=  PoolFormerConfigTester(self      ,					config_class=__snake_case       )
     def 						lowerCamelCase_     (			self     :    int       ):
         self.config_tester.run_common_tests()
     def 						lowerCamelCase_     (			self     :    int       ):
         UpperCAmelCase_											=  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 						lowerCamelCase_     (			self     :    Optional[Any]       ):
         pass
     @unittest.skip('''PoolFormer does not have get_input_embeddings method and get_output_embeddings methods'''       )
     def 						lowerCamelCase_     (			self     :    Optional[int]       ):
         pass
     def 						lowerCamelCase_     (			self     :    Tuple       ):
         def check_hidden_states_output(__snake_case     :    Dict      ,					__snake_case     :    str      ,					__snake_case     :    List[Any]       ):
             UpperCAmelCase_											=  model_class(__snake_case       )
             model.to(__snake_case       )
             model.eval()

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

             UpperCAmelCase_											=  outputs.hidden_states

             UpperCAmelCase_											=  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,
                 ]      ,					)

         UpperCAmelCase_				,							UpperCAmelCase_											=  self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             UpperCAmelCase_											=  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"]
             UpperCAmelCase_											=  True

             check_hidden_states_output(__snake_case      ,					__snake_case      ,					__snake_case       )
     def 						lowerCamelCase_     (			self     :    Dict       ):
         if not self.model_tester.is_training:
             return

         UpperCAmelCase_				,							UpperCAmelCase_											=  self.model_tester.prepare_config_and_inputs_for_common()
         UpperCAmelCase_											=  True

         for model_class in self.all_model_classes:
             if model_class in get_values(__snake_case       ):
                 continue
             UpperCAmelCase_											=  model_class(__snake_case       )
             model.to(__snake_case       )
             model.train()
             UpperCAmelCase_											=  self._prepare_for_class(__snake_case      ,					__snake_case      ,					return_labels=__snake_case       )
             UpperCAmelCase_											=  model(**__snake_case       ).loss
             loss.backward()
     def 						lowerCamelCase_     (			self     :    List[Any]       ):
         UpperCAmelCase_				,							UpperCAmelCase_											=  self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             UpperCAmelCase_											=  model_class(__snake_case       )
             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]      ,					__snake_case       )




     @slow
     def 						lowerCamelCase_     (			self     :    int       ):
         for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             UpperCAmelCase_											=  PoolFormerModel.from_pretrained(__snake_case       )
             self.assertIsNotNone(__snake_case       )




def       SCREAMING_SNAKE_CASE			( )						->							Tuple:
    UpperCAmelCase_											=  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
    return image



@require_torch
class     a  (     unittest.TestCase    ):

     '''simple docstring'''





     @slow
     def 						lowerCamelCase_     (			self     :    Optional[int]       ):
         UpperCAmelCase_											=  PoolFormerImageProcessor()
         UpperCAmelCase_											=  PoolFormerForImageClassification.from_pretrained('''sail/poolformer_s12'''       ).to(__snake_case       )

         UpperCAmelCase_											=  image_processor(images=prepare_img()      ,					return_tensors='''pt'''       ).to(__snake_case       )

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

         # verify the logits
         UpperCAmelCase_											=  torch.Size((1, 10_00)       )
         self.assertEqual(outputs.logits.shape      ,					__snake_case       )

         UpperCAmelCase_											=  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       )       )











import logging
import os
import sys
import threading
from logging import (
    CRITICAL,  # NOQA
    DEBUG,  # NOQA
    ERROR,  # NOQA
    FATAL,  # NOQA
    INFO,  # NOQA
    NOTSET,  # NOQA
    WARN,  # NOQA
    WARNING,  # NOQA
)
from typing import Optional

from tqdm import auto as tqdm_lib


_lowerCamelCase    				=		threading.Lock()
_lowerCamelCase    				=		None

_lowerCamelCase    				=		{
    'debug': logging.DEBUG,
    'info': logging.INFO,
    'warning': logging.WARNING,
    'error': logging.ERROR,
    'critical': logging.CRITICAL,
}

_lowerCamelCase    				=		logging.WARNING

_lowerCamelCase    				=		True




def       SCREAMING_SNAKE_CASE			( )						->							List[str]:
    UpperCAmelCase_											=  os.getenv('''DIFFUSERS_VERBOSITY''' ,  __UpperCamelCase   )
    if env_level_str:
        if env_level_str in log_levels:
            return log_levels[env_level_str]
        else:
            logging.getLogger().warning(
                f'Unknown option DIFFUSERS_VERBOSITY={env_level_str}, '
                f'has to be one of: { ", ".join(log_levels.keys()   ) }'   )
    return _default_log_level




def       SCREAMING_SNAKE_CASE			( )						->							str:
    return __name__.split('''.'''   )[0]




def       SCREAMING_SNAKE_CASE			( )						->							logging.Logger:
    return logging.getLogger(_get_library_name()   )




def       SCREAMING_SNAKE_CASE			( )						->							None:
    global _default_handler

    with _lock:
        if _default_handler:
            # This library has already configured the library root logger.
            return
        UpperCAmelCase_											=  logging.StreamHandler()  # Set sys.stderr as stream.
        UpperCAmelCase_											=  sys.stderr.flush

        # Apply our default configuration to the library root logger.
        UpperCAmelCase_											=  _get_library_root_logger()
        library_root_logger.addHandler(_default_handler   )
        library_root_logger.setLevel(_get_default_logging_level()   )
        UpperCAmelCase_											=  False




def       SCREAMING_SNAKE_CASE			( )						->							None:
    global _default_handler

    with _lock:
        if not _default_handler:
            return

        UpperCAmelCase_											=  _get_library_root_logger()
        library_root_logger.removeHandler(_default_handler   )
        library_root_logger.setLevel(logging.NOTSET   )
        UpperCAmelCase_											=  None




def       SCREAMING_SNAKE_CASE			( )						->							Dict:
    return log_levels




def       SCREAMING_SNAKE_CASE			( __UpperCamelCase    :		Optional[str] = None   )						->							logging.Logger:

    if name is None:
        UpperCAmelCase_											=  _get_library_name()

    _configure_library_root_logger()
    return logging.getLogger(__UpperCamelCase   )




def       SCREAMING_SNAKE_CASE			( )						->							int:
    _configure_library_root_logger()
    return _get_library_root_logger().getEffectiveLevel()




def       SCREAMING_SNAKE_CASE			( __UpperCamelCase    :		int   )						->							None:
    _configure_library_root_logger()
    _get_library_root_logger().setLevel(__UpperCamelCase   )




def       SCREAMING_SNAKE_CASE			( )						->							Optional[Any]:
    return set_verbosity(__UpperCamelCase   )




def       SCREAMING_SNAKE_CASE			( )						->							Union[str, Any]:
    return set_verbosity(__UpperCamelCase   )




def       SCREAMING_SNAKE_CASE			( )						->							Tuple:
    return set_verbosity(__UpperCamelCase   )




def       SCREAMING_SNAKE_CASE			( )						->							int:
    return set_verbosity(__UpperCamelCase   )




def       SCREAMING_SNAKE_CASE			( )						->							None:
    _configure_library_root_logger()

    assert _default_handler is not None
    _get_library_root_logger().removeHandler(_default_handler   )




def       SCREAMING_SNAKE_CASE			( )						->							None:
    _configure_library_root_logger()

    assert _default_handler is not None
    _get_library_root_logger().addHandler(_default_handler   )




def       SCREAMING_SNAKE_CASE			( __UpperCamelCase    :		logging.Handler   )						->							None:
    _configure_library_root_logger()

    assert handler is not None
    _get_library_root_logger().addHandler(__UpperCamelCase   )




def       SCREAMING_SNAKE_CASE			( __UpperCamelCase    :		logging.Handler   )						->							None:
    _configure_library_root_logger()

    assert handler is not None and handler not in _get_library_root_logger().handlers
    _get_library_root_logger().removeHandler(__UpperCamelCase   )




def       SCREAMING_SNAKE_CASE			( )						->							None:
    _configure_library_root_logger()
    UpperCAmelCase_											=  False




def       SCREAMING_SNAKE_CASE			( )						->							None:
    _configure_library_root_logger()
    UpperCAmelCase_											=  True




def       SCREAMING_SNAKE_CASE			( )						->							None:
    UpperCAmelCase_											=  _get_library_root_logger().handlers

    for handler in handlers:
        UpperCAmelCase_											=  logging.Formatter('''[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s'''   )
        handler.setFormatter(__UpperCamelCase   )




def       SCREAMING_SNAKE_CASE			( )						->							None:
    UpperCAmelCase_											=  _get_library_root_logger().handlers

    for handler in handlers:
        handler.setFormatter(__UpperCamelCase   )




def       SCREAMING_SNAKE_CASE			( self    :		Tuple ,  *__UpperCamelCase    :		Any ,  **__UpperCamelCase    :		Any   )						->							Union[str, Any]:
    UpperCAmelCase_											=  os.getenv('''DIFFUSERS_NO_ADVISORY_WARNINGS''' ,  __UpperCamelCase   )
    if no_advisory_warnings:
        return
    self.warning(*__UpperCamelCase ,  **__UpperCamelCase   )


_lowerCamelCase    				=		warning_advice



class     a  :

     '''simple docstring'''





     def __init__(			self     :    List[Any]      ,					*__snake_case     :    Tuple      ,					**__snake_case     :    str       ):  # pylint: disable=unused-argument
         UpperCAmelCase_											=  args[0] if args else None
     def __iter__(			self     :    Union[str, Any]       ):
         return iter(self._iterator       )
     def __getattr__(			self     :    Tuple      ,					__snake_case     :    str       ):

         def empty_fn(*__snake_case     :    Optional[int]      ,					**__snake_case     :    int       ):  # pylint: disable=unused-argument
             return

         return empty_fn
     def __enter__(			self     :    Optional[Any]       ):
         return self




     def __exit__(			self     :    Union[str, Any]      ,					__snake_case     :    List[Any]      ,					__snake_case     :    List[str]      ,					__snake_case     :    Dict       ):
         return



class     a  :

     '''simple docstring'''





     def __call__(			self     :    Union[str, Any]      ,					*__snake_case     :    List[str]      ,					**__snake_case     :    Dict       ):
         if _tqdm_active:
             return tqdm_lib.tqdm(*__snake_case      ,					**__snake_case       )
         else:
             return EmptyTqdm(*__snake_case      ,					**__snake_case       )
     def 						lowerCamelCase_     (			self     :    int      ,					*__snake_case     :    Dict      ,					**__snake_case     :    List[str]       ):
         UpperCAmelCase_											=  None
         if _tqdm_active:
             return tqdm_lib.tqdm.set_lock(*__snake_case      ,					**__snake_case       )




     def 						lowerCamelCase_     (			self     :    str       ):
         if _tqdm_active:
             return tqdm_lib.tqdm.get_lock()


_lowerCamelCase    				=		_tqdm_cls()




def       SCREAMING_SNAKE_CASE			( )						->							bool:
    global _tqdm_active
    return bool(_tqdm_active   )




def       SCREAMING_SNAKE_CASE			( )						->							List[str]:
    global _tqdm_active
    UpperCAmelCase_											=  True




def       SCREAMING_SNAKE_CASE			( )						->							Optional[int]:
    global _tqdm_active
    UpperCAmelCase_											=  False





