'''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(     _lowerCamelCase				):



   """simple docstring"""





   def 			snake_case	(							self:    str	):
    __UpperCAmelCase         =					self.config_class(**self.inputs_dict	)
    self.parent.assertTrue(hasattr(a			,'hidden_sizes'	)	)
    self.parent.assertTrue(hasattr(a			,'num_encoder_blocks'	)	)




class   _lowercase:



   """simple docstring"""





   def __init__(							self:    Dict			,a:    int			,a:    Tuple=13			,a:    str=64			,a:    Dict=3			,a:    str=4			,a:    Union[str, Any]=[2, 2, 2, 2]			,a:    List[str]=[8, 4, 2, 1]			,a:    List[str]=[16, 32, 64, 128]			,a:    Optional[int]=[1, 4, 8, 16]			,a:    List[Any]=False			,a:    Dict=True			,a:    Optional[Any]="gelu"			,a:    List[str]=0.1			,a:    List[Any]=0.02			,a:    Optional[int]=3			,a:    Optional[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 			snake_case	(							self:    Optional[int]	):
    __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 			snake_case	(							self:    Tuple			,a:    Dict			,a:    Optional[Any]			,a:    str	):
    __UpperCAmelCase         =					PoolFormerModel(config=a	)
    model.to(a	)
    model.eval()
    __UpperCAmelCase         =					model(a	)
    __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 			snake_case	(							self:    Tuple	):
    __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(     _lowerCamelCase   ,_lowerCamelCase   ,unittest.TestCase				):



   """simple docstring"""





   __lowerCamelCase    =  (PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
   __lowerCamelCase    =  (
       {'''feature-extraction''': PoolFormerModel, '''image-classification''': PoolFormerForImageClassification}
       if is_torch_available()
       else {}
   )

   __lowerCamelCase    =  False
   __lowerCamelCase    =  False
   __lowerCamelCase    =  False
   __lowerCamelCase    =  False
   __lowerCamelCase    =  False





   def 			snake_case	(							self:    List[str]	):
    __UpperCAmelCase         =					PoolFormerModelTester(self	)
    __UpperCAmelCase         =					PoolFormerConfigTester(self			,config_class=a	)





   def 			snake_case	(							self:    Optional[Any]	):
    self.config_tester.run_common_tests()





   def 			snake_case	(							self:    List[Any]	):
    __UpperCAmelCase         =					self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*a	)





   @unittest.skip('PoolFormer does not use inputs_embeds'	)
   def 			snake_case	(							self:    str	):
    pass





   @unittest.skip('PoolFormer does not have get_input_embeddings method and get_output_embeddings methods'	)
   def 			snake_case	(							self:    Optional[int]	):
    pass





   def 			snake_case	(							self:    Any	):
    def check_hidden_states_output(a:    Optional[int]			,a:    List[Any]			,a:    Any	):
     __UpperCAmelCase         =					model_class(a	)
     model.to(a	)
     model.eval()

     with torch.no_grad():
      __UpperCAmelCase         =					model(**self._prepare_for_class(a			,a	)	)

     __UpperCAmelCase         =					outputs.hidden_states

     __UpperCAmelCase         =					self.model_tester.num_encoder_blocks
     self.assertEqual(len(a	)			,a	)

     # 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(a			,a			,a	)

     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     __UpperCAmelCase         =					True

     check_hidden_states_output(a			,a			,a	)





   def 			snake_case	(							self:    str	):
    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(a	):
      continue
     __UpperCAmelCase         =					model_class(a	)
     model.to(a	)
     model.train()
     __UpperCAmelCase         =					self._prepare_for_class(a			,a			,return_labels=a	)
     __UpperCAmelCase         =					model(**a	).loss
     loss.backward()





   def 			snake_case	(							self:    Union[str, Any]	):
    __UpperCAmelCase  ,			__UpperCAmelCase         =					self.model_tester.prepare_config_and_inputs_for_common()

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





   @slow
   def 			snake_case	(							self:    List[Any]	):
    for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     __UpperCAmelCase         =					PoolFormerModel.from_pretrained(a	)
     self.assertIsNotNone(a	)




def 						__snake_case (       ):
 __UpperCAmelCase         =					Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
 return image

@require_torch
class   _lowercase(     unittest.TestCase				):



   """simple docstring"""





   @slow
   def 			snake_case	(							self:    Dict	):
    __UpperCAmelCase         =					PoolFormerImageProcessor()
    __UpperCAmelCase         =					PoolFormerForImageClassification.from_pretrained('sail/poolformer_s12'	).to(a	)

    __UpperCAmelCase         =					image_processor(images=prepare_img()			,return_tensors='pt'	).to(a	)

    # forward pass
    with torch.no_grad():
     __UpperCAmelCase         =					model(**a	)

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

    __UpperCAmelCase         =					torch.tensor([-0.6113, 0.1685, -0.0492]	).to(a	)
    self.assertTrue(torch.allclose(outputs.logits[0, :3]			,a			,atol=1e-4	)	)




'''simple docstring'''




from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_sentencepiece_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


_UpperCamelCase				:		Dict       			=		{
    'configuration_marian': ['MARIAN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MarianConfig', 'MarianOnnxConfig'],
}

try:
     if not is_sentencepiece_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     _UpperCamelCase				:		Optional[int]       			=		['MarianTokenizer']

try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     _UpperCamelCase				:		Dict       			=		[
         'MARIAN_PRETRAINED_MODEL_ARCHIVE_LIST',
         'MarianForCausalLM',
         'MarianModel',
         'MarianMTModel',
         'MarianPreTrainedModel',
     ]

try:
     if not is_tf_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     _UpperCamelCase				:		Dict       			=		['TFMarianModel', 'TFMarianMTModel', 'TFMarianPreTrainedModel']

try:
     if not is_flax_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     _UpperCamelCase				:		Any       			=		['FlaxMarianModel', 'FlaxMarianMTModel', 'FlaxMarianPreTrainedModel']

if TYPE_CHECKING:
     from .configuration_marian import MARIAN_PRETRAINED_CONFIG_ARCHIVE_MAP, MarianConfig, MarianOnnxConfig

     try:
          if not is_sentencepiece_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .tokenization_marian import MarianTokenizer

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_marian import (
              MARIAN_PRETRAINED_MODEL_ARCHIVE_LIST,
              MarianForCausalLM,
              MarianModel,
              MarianMTModel,
              MarianPreTrainedModel,
          )

     try:
          if not is_tf_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_tf_marian import TFMarianModel, TFMarianMTModel, TFMarianPreTrainedModel

     try:
          if not is_flax_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_flax_marian import FlaxMarianModel, FlaxMarianMTModel, FlaxMarianPreTrainedModel

else:
     import sys

     _UpperCamelCase				:		List[Any]       			=		_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)



