





from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
      import tensorflow as tf

      from transformers import TFResNetForImageClassification, TFResNetModel
      from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor





class      lowercase__    :







  def __init__(	self    ,						_lowercase    ,						_lowercase=3    ,						_lowercase=32    ,						_lowercase=3    ,						_lowercase=10    ,						_lowercase=[10, 20, 30, 40]    ,						_lowercase=[1, 1, 2, 1]    ,						_lowercase=True    ,						_lowercase=True    ,						_lowercase="relu"    ,						_lowercase=3    ,						_lowercase=None    ,						):
       lowerCAmelCase_					:       Union[str, Any]    =		parent
       lowerCAmelCase_					:       int    =		batch_size
       lowerCAmelCase_					:       int    =		image_size
       lowerCAmelCase_					:       List[str]    =		num_channels
       lowerCAmelCase_					:       Optional[int]    =		embeddings_size
       lowerCAmelCase_					:       Optional[int]    =		hidden_sizes
       lowerCAmelCase_					:       str    =		depths
       lowerCAmelCase_					:       str    =		is_training
       lowerCAmelCase_					:       int    =		use_labels
       lowerCAmelCase_					:       Optional[int]    =		hidden_act
       lowerCAmelCase_					:       Optional[int]    =		num_labels
       lowerCAmelCase_					:       Dict    =		scope
       lowerCAmelCase_					:       Union[str, Any]    =		len(_A						)







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Optional[int]    =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

       lowerCAmelCase_					:       Optional[Any]    =		None
       if self.use_labels:
            lowerCAmelCase_					:       List[Any]    =		ids_tensor([self.batch_size]    ,						self.num_labels						)

       lowerCAmelCase_					:       Union[str, Any]    =		self.get_config()

       return config, pixel_values, labels







  def 	UpperCAmelCase__		(	self						):
       return ResNetConfig(
           num_channels=self.num_channels    ,						embeddings_size=self.embeddings_size    ,						hidden_sizes=self.hidden_sizes    ,						depths=self.depths    ,						hidden_act=self.hidden_act    ,						num_labels=self.num_labels    ,						image_size=self.image_size    ,						)







  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase    ,						_lowercase						):
       lowerCAmelCase_					:       Optional[Any]    =		TFResNetModel(config=_A						)
       lowerCAmelCase_					:       List[str]    =		model(_A						)
       # expected last hidden states: B, C, H // 32, W // 32
       self.parent.assertEqual(
           result.last_hidden_state.shape    ,						(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)    ,						)







  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase    ,						_lowercase						):
       lowerCAmelCase_					:       Any    =		self.num_labels
       lowerCAmelCase_					:       Dict    =		TFResNetForImageClassification(_A						)
       lowerCAmelCase_					:       int    =		model(_A    ,						labels=_A						)
       self.parent.assertEqual(result.logits.shape    ,						(self.batch_size, self.num_labels)						)







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Union[str, Any]    =		self.prepare_config_and_inputs()
       lowerCAmelCase_					:       Tuple    =		config_and_inputs
       lowerCAmelCase_					:       Any    =		{'pixel_values': pixel_values}
       return config, inputs_dict





@require_tf
class      lowercase__    (							a__     ,					a__     ,					unittest.TestCase  ):
  __UpperCamelCase	     =  (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
  __UpperCamelCase	     =  (
      {"""feature-extraction""": TFResNetModel, """image-classification""": TFResNetForImageClassification}
      if is_tf_available()
      else {}
  )

  __UpperCamelCase	     =  False
  __UpperCamelCase	     =  False
  __UpperCamelCase	     =  False
  __UpperCamelCase	     =  False
  __UpperCamelCase	     =  False







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       List[str]    =		TFResNetModelTester(self						)
       lowerCAmelCase_					:       List[str]    =		ConfigTester(self    ,						config_class=_A    ,						has_text_modality=_A						)







  def 	UpperCAmelCase__		(	self						):
       self.create_and_test_config_common_properties()
       self.config_tester.create_and_test_config_to_json_string()
       self.config_tester.create_and_test_config_to_json_file()
       self.config_tester.create_and_test_config_from_and_save_pretrained()
       self.config_tester.create_and_test_config_with_num_labels()
       self.config_tester.check_config_can_be_init_without_params()
       self.config_tester.check_config_arguments_init()







  def 	UpperCAmelCase__		(	self						):
       return







  @unittest.skip(reason="""ResNet does not use inputs_embeds"""						)
  def 	UpperCAmelCase__		(	self						):
       pass







  @unittest.skip(reason="""ResNet does not support input and output embeddings"""						)
  def 	UpperCAmelCase__		(	self						):
       pass







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Optional[int]    =		self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            lowerCAmelCase_					:       int    =		model_class(_A						)
            lowerCAmelCase_					:       Union[str, Any]    =		inspect.signature(model.call						)
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            lowerCAmelCase_					:       Any    =		[*signature.parameters.keys()]

            lowerCAmelCase_					:       str    =		['pixel_values']
            self.assertListEqual(arg_names[:1]    ,						_A						)







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Dict    =		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_A						)







  def 	UpperCAmelCase__		(	self						):

       def check_hidden_states_output(_lowercase    ,						_lowercase    ,						_lowercase						):
            lowerCAmelCase_					:       int    =		model_class(_A						)
            lowerCAmelCase_					:       int    =		model(**self._prepare_for_class(_A    ,						_A						)						)

            lowerCAmelCase_					:       Dict    =		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

            lowerCAmelCase_					:       int    =		self.model_tester.num_stages
            self.assertEqual(len(_A						)    ,						expected_num_stages + 1						)

            # ResNet's feature maps are of shape (batch_size, num_channels, height, width)
            self.assertListEqual(
                list(hidden_states[0].shape[-2:]						)    ,						[self.model_tester.image_size // 4, self.model_tester.image_size // 4]    ,						)

       lowerCAmelCase_					:       List[str]    =		self.model_tester.prepare_config_and_inputs_for_common()
       lowerCAmelCase_					:       Any    =		['basic', 'bottleneck']
       for model_class in self.all_model_classes:
            for layer_type in layers_type:
                 lowerCAmelCase_					:       Optional[int]    =		layer_type
                 lowerCAmelCase_					:       Tuple    =		True
                 check_hidden_states_output(_A    ,						_A    ,						_A						)

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

                 check_hidden_states_output(_A    ,						_A    ,						_A						)







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       str    =		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_A						)







  @slow
  def 	UpperCAmelCase__		(	self						):

       for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            lowerCAmelCase_					:       Optional[Any]    =		TFResNetModel.from_pretrained(_A						)
            self.assertIsNotNone(_A						)






def 							_lowerCAmelCase (  )	->			Optional[int]:
     lowerCAmelCase_					:       Tuple    =		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
     return image







@require_tf
@require_vision
class      lowercase__    (							unittest.TestCase  ):







  @cached_property
  def 	UpperCAmelCase__		(	self						):
       return (
           AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)
           if is_vision_available()
           else None
       )







  @slow
  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       str    =		TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)

       lowerCAmelCase_					:       Tuple    =		self.default_image_processor
       lowerCAmelCase_					:       Optional[Any]    =		prepare_img()
       lowerCAmelCase_					:       int    =		image_processor(images=_A    ,						return_tensors="""tf"""						)

       # forward pass
       lowerCAmelCase_					:       int    =		model(**_A						)

       # verify the logits
       lowerCAmelCase_					:       Optional[Any]    =		tf.TensorShape((1, 1_000)						)
       self.assertEqual(outputs.logits.shape    ,						_A						)

       lowerCAmelCase_					:       Any    =		tf.constant([-11.1_069, -9.7877, -8.3777]						)

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







from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase_					:   Tuple 							=						logging.get_logger(__name__)

UpperCAmelCase_					:   List[str] 							=						{
    """google/fnet-base""": """https://huggingface.co/google/fnet-base/resolve/main/config.json""",
    """google/fnet-large""": """https://huggingface.co/google/fnet-large/resolve/main/config.json"""
    # See all FNet models at https://huggingface.co/models?filter=fnet
}





class      lowercase__    (							__A  ):
  __UpperCamelCase	     =  """fnet"""







  def __init__(	self    ,						_lowercase=32_000    ,						_lowercase=768    ,						_lowercase=12    ,						_lowercase=3_072    ,						_lowercase="gelu_new"    ,						_lowercase=0.1    ,						_lowercase=512    ,						_lowercase=4    ,						_lowercase=0.02    ,						_lowercase=1e-12    ,						_lowercase=False    ,						_lowercase=512    ,						_lowercase=3    ,						_lowercase=1    ,						_lowercase=2    ,						**_lowercase    ,						):
       super().__init__(pad_token_id=_lowercase    ,						bos_token_id=_lowercase    ,						eos_token_id=_lowercase    ,						**_lowercase						)

       lowerCAmelCase_					:       Optional[Any]    =		vocab_size
       lowerCAmelCase_					:       List[str]    =		max_position_embeddings
       lowerCAmelCase_					:       str    =		hidden_size
       lowerCAmelCase_					:       Any    =		num_hidden_layers
       lowerCAmelCase_					:       Optional[int]    =		intermediate_size
       lowerCAmelCase_					:       int    =		hidden_act
       lowerCAmelCase_					:       List[str]    =		hidden_dropout_prob
       lowerCAmelCase_					:       Tuple    =		initializer_range
       lowerCAmelCase_					:       int    =		type_vocab_size
       lowerCAmelCase_					:       str    =		layer_norm_eps
       lowerCAmelCase_					:       Optional[Any]    =		use_tpu_fourier_optimizations
       lowerCAmelCase_					:       Union[str, Any]    =		tpu_short_seq_length
