


import inspect
import unittest

from transformers import ResNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
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 torch import nn

      from transformers import ResNetBackbone, ResNetForImageClassification, ResNetModel
      from transformers.models.resnet.modeling_resnet import RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor





class      UpperCAmelCase_						:





    """simple docstring"""






    def __init__(							self    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_=3    ,  SCREAMING_SNAKE_CASE_=32    ,  SCREAMING_SNAKE_CASE_=3    ,  SCREAMING_SNAKE_CASE_=10    ,  SCREAMING_SNAKE_CASE_=[10, 20, 30, 40]    ,  SCREAMING_SNAKE_CASE_=[1, 1, 2, 1]    ,  SCREAMING_SNAKE_CASE_=True    ,  SCREAMING_SNAKE_CASE_=True    ,  SCREAMING_SNAKE_CASE_="relu"    ,  SCREAMING_SNAKE_CASE_=3    ,  SCREAMING_SNAKE_CASE_=None    ,  SCREAMING_SNAKE_CASE_=["stage2", "stage3", "stage4"]    ,  SCREAMING_SNAKE_CASE_=[2, 3, 4]    ,  )       ->  int:
         __lowerCamelCase     :			Dict              =	parent
         __lowerCamelCase     :			List[str]              =	batch_size
         __lowerCamelCase     :			List[str]              =	image_size
         __lowerCamelCase     :			Optional[int]              =	num_channels
         __lowerCamelCase     :			Union[str, Any]              =	embeddings_size
         __lowerCamelCase     :			Optional[int]              =	hidden_sizes
         __lowerCamelCase     :			Optional[Any]              =	depths
         __lowerCamelCase     :			List[str]              =	is_training
         __lowerCamelCase     :			List[str]              =	use_labels
         __lowerCamelCase     :			str              =	hidden_act
         __lowerCamelCase     :			List[str]              =	num_labels
         __lowerCamelCase     :			Any              =	scope
         __lowerCamelCase     :			str              =	len(SCREAMING_SNAKE_CASE_			)
         __lowerCamelCase     :			Tuple              =	out_features
         __lowerCamelCase     :			List[Any]              =	out_indices







    def    lowercase_       (							self			)       ->  str:
         __lowerCamelCase     :			List[Any]              =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

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

         __lowerCamelCase     :			Dict              =	self.get_config()

         return config, pixel_values, labels







    def    lowercase_       (							self			)       ->  int:
         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    ,  out_features=self.out_features    ,  out_indices=self.out_indices    ,  )







    def    lowercase_       (							self    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_			)       ->  Optional[int]:
         __lowerCamelCase     :			Dict              =	ResNetModel(config=SCREAMING_SNAKE_CASE_			)
         model.to(SCREAMING_SNAKE_CASE_			)
         model.eval()
         __lowerCamelCase     :			Dict              =	model(SCREAMING_SNAKE_CASE_			)
         # 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    lowercase_       (							self    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_			)       ->  Any:
         __lowerCamelCase     :			Union[str, Any]              =	self.num_labels
         __lowerCamelCase     :			Any              =	ResNetForImageClassification(SCREAMING_SNAKE_CASE_			)
         model.to(SCREAMING_SNAKE_CASE_			)
         model.eval()
         __lowerCamelCase     :			Any              =	model(SCREAMING_SNAKE_CASE_    ,  labels=SCREAMING_SNAKE_CASE_			)
         self.parent.assertEqual(result.logits.shape    ,  (self.batch_size, self.num_labels)			)







    def    lowercase_       (							self    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_			)       ->  Optional[Any]:
         __lowerCamelCase     :			Dict              =	ResNetBackbone(config=SCREAMING_SNAKE_CASE_			)
         model.to(SCREAMING_SNAKE_CASE_			)
         model.eval()
         __lowerCamelCase     :			int              =	model(SCREAMING_SNAKE_CASE_			)

         # verify feature maps
         self.parent.assertEqual(len(result.feature_maps			)    ,  len(config.out_features			)			)
         self.parent.assertListEqual(list(result.feature_maps[0].shape			)    ,  [self.batch_size, self.hidden_sizes[1], 4, 4]			)

         # verify channels
         self.parent.assertEqual(len(model.channels			)    ,  len(config.out_features			)			)
         self.parent.assertListEqual(model.channels    ,  config.hidden_sizes[1:]			)

         # verify backbone works with out_features=None
         __lowerCamelCase     :			Tuple              =	None
         __lowerCamelCase     :			Optional[int]              =	ResNetBackbone(config=SCREAMING_SNAKE_CASE_			)
         model.to(SCREAMING_SNAKE_CASE_			)
         model.eval()
         __lowerCamelCase     :			Optional[int]              =	model(SCREAMING_SNAKE_CASE_			)

         # verify feature maps
         self.parent.assertEqual(len(result.feature_maps			)    ,  1			)
         self.parent.assertListEqual(list(result.feature_maps[0].shape			)    ,  [self.batch_size, self.hidden_sizes[-1], 1, 1]			)

         # verify channels
         self.parent.assertEqual(len(model.channels			)    ,  1			)
         self.parent.assertListEqual(model.channels    ,  [config.hidden_sizes[-1]]			)







    def    lowercase_       (							self			)       ->  str:
         __lowerCamelCase     :			str              =	self.prepare_config_and_inputs()
         __lowerCamelCase     :			Optional[int]              =	config_and_inputs
         __lowerCamelCase     :			Any              =	{'pixel_values': pixel_values}
         return config, inputs_dict







@require_torch
class      UpperCAmelCase_						(_UpperCAmelCase      ,	_UpperCAmelCase      ,	unittest.TestCase						):





    """simple docstring"""






    lowerCamelCase						:      Optional[Any]							  =    (
        (
            ResNetModel,
            ResNetForImageClassification,
            ResNetBackbone,
        )
        if is_torch_available()
        else ()
    )
    lowerCamelCase						:      List[Any]							  =    (
        {'feature-extraction': ResNetModel, 'image-classification': ResNetForImageClassification}
        if is_torch_available()
        else {}
    )

    lowerCamelCase						:      str							  =    True
    lowerCamelCase						:      Tuple							  =    False
    lowerCamelCase						:      List[str]							  =    False
    lowerCamelCase						:      Any							  =    False
    lowerCamelCase						:      List[str]							  =    False







    def    lowercase_       (							self			)       ->  List[str]:
         __lowerCamelCase     :			Optional[Any]              =	ResNetModelTester(self			)
         __lowerCamelCase     :			Tuple              =	ConfigTester(self    ,  config_class=SCREAMING_SNAKE_CASE_    ,  has_text_modality=SCREAMING_SNAKE_CASE_			)







    def    lowercase_       (							self			)       ->  str:
         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    lowercase_       (							self			)       ->  Tuple:
         return







    @unittest.skip(reason='ResNet does not use inputs_embeds'			)
    def    lowercase_       (							self			)       ->  Dict:
         pass







    @unittest.skip(reason='ResNet does not support input and output embeddings'			)
    def    lowercase_       (							self			)       ->  List[Any]:
         pass







    def    lowercase_       (							self			)       ->  Any:
         __lowerCamelCase     :			Union[str, Any]              =	self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              __lowerCamelCase     :			str              =	model_class(SCREAMING_SNAKE_CASE_			)
              __lowerCamelCase     :			Optional[Any]              =	inspect.signature(model.forward			)
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              __lowerCamelCase     :			Union[str, Any]              =	[*signature.parameters.keys()]

              __lowerCamelCase     :			List[str]              =	['pixel_values']
              self.assertListEqual(arg_names[:1]    ,  SCREAMING_SNAKE_CASE_			)







    def    lowercase_       (							self			)       ->  Tuple:
         __lowerCamelCase     :			str              =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_			)







    def    lowercase_       (							self			)       ->  Optional[Any]:
         __lowerCamelCase     :			List[str]              =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_backbone(*SCREAMING_SNAKE_CASE_			)







    def    lowercase_       (							self			)       ->  Union[str, Any]:
         __lowerCamelCase     :			Union[str, Any]              =	self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              __lowerCamelCase     :			Any              =	model_class(config=SCREAMING_SNAKE_CASE_			)
              for name, module in model.named_modules():
                   if isinstance(SCREAMING_SNAKE_CASE_    ,  (nn.BatchNormad, nn.GroupNorm)			):
                        self.assertTrue(
                            torch.all(module.weight == 1			)    ,  msg=f'Parameter {name} of model {model_class} seems not properly initialized'    ,  )
                        self.assertTrue(
                            torch.all(module.bias == 0			)    ,  msg=f'Parameter {name} of model {model_class} seems not properly initialized'    ,  )







    def    lowercase_       (							self			)       ->  str:
         def check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_			):
              __lowerCamelCase     :			Optional[Any]              =	model_class(SCREAMING_SNAKE_CASE_			)
              model.to(SCREAMING_SNAKE_CASE_			)
              model.eval()

              with torch.no_grad():
                   __lowerCamelCase     :			int              =	model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_			)			)

              __lowerCamelCase     :			Any              =	outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

              __lowerCamelCase     :			Union[str, Any]              =	self.model_tester.num_stages
              self.assertEqual(len(SCREAMING_SNAKE_CASE_			)    ,  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     :			Dict              =	self.model_tester.prepare_config_and_inputs_for_common()
         __lowerCamelCase     :			List[Any]              =	['basic', 'bottleneck']
         for model_class in self.all_model_classes:
              for layer_type in layers_type:
                   __lowerCamelCase     :			List[str]              =	layer_type
                   __lowerCamelCase     :			List[str]              =	True
                   check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_			)

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

                   check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_			)







    @unittest.skip(reason='ResNet does not use feedforward chunking'			)
    def    lowercase_       (							self			)       ->  Union[str, Any]:
         pass







    def    lowercase_       (							self			)       ->  Tuple:
         __lowerCamelCase     :			Dict              =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_			)







    @slow
    def    lowercase_       (							self			)       ->  Dict:
         for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              __lowerCamelCase     :			Tuple              =	ResNetModel.from_pretrained(SCREAMING_SNAKE_CASE_			)
              self.assertIsNotNone(SCREAMING_SNAKE_CASE_			)







def     UpperCAmelCase__      (			)  ->	Optional[Any]:
     __lowerCamelCase     :			int              =	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
     return image





@require_torch
@require_vision
class      UpperCAmelCase_						(unittest.TestCase						):





    """simple docstring"""






    @cached_property
    def    lowercase_       (							self			)       ->  int:
         return (
             AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]			)
             if is_vision_available()
             else None
         )







    @slow
    def    lowercase_       (							self			)       ->  Any:
         __lowerCamelCase     :			Any              =	ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]			).to(SCREAMING_SNAKE_CASE_			)

         __lowerCamelCase     :			Dict              =	self.default_image_processor
         __lowerCamelCase     :			Optional[int]              =	prepare_img()
         __lowerCamelCase     :			Any              =	image_processor(images=SCREAMING_SNAKE_CASE_    ,  return_tensors='pt'			).to(SCREAMING_SNAKE_CASE_			)

         # forward pass
         with torch.no_grad():
              __lowerCamelCase     :			Tuple              =	model(**SCREAMING_SNAKE_CASE_			)

         # verify the logits
         __lowerCamelCase     :			Optional[int]              =	torch.Size((1, 10_00)			)
         self.assertEqual(outputs.logits.shape    ,  SCREAMING_SNAKE_CASE_			)

         __lowerCamelCase     :			Dict              =	torch.tensor([-11.10_69, -9.7_8_7_7, -8.3_7_7_7]			).to(SCREAMING_SNAKE_CASE_			)

         self.assertTrue(torch.allclose(outputs.logits[0, :3]    ,  SCREAMING_SNAKE_CASE_    ,  atol=1E-4			)			)







@require_torch
class      UpperCAmelCase_						(_UpperCAmelCase      ,	unittest.TestCase						):





    """simple docstring"""






    lowerCamelCase						:      str							  =    (ResNetBackbone,) if is_torch_available() else ()
    lowerCamelCase						:      Any							  =    False
    lowerCamelCase						:      Union[str, Any]							  =    ResNetConfig







    def    lowercase_       (							self			)       ->  List[str]:
         __lowerCamelCase     :			str              =	ResNetModelTester(self			)










'''simple docstring'''



from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available


A__	:      Optional[Any]				=						{
    """configuration_xlm_prophetnet""": ["""XLM_PROPHETNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLMProphetNetConfig"""],
}

try:
      if not is_sentencepiece_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      A__	:      List[Any]				=						["""XLMProphetNetTokenizer"""]

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      A__	:      Optional[Any]				=						[
          """XLM_PROPHETNET_PRETRAINED_MODEL_ARCHIVE_LIST""",
          """XLMProphetNetDecoder""",
          """XLMProphetNetEncoder""",
          """XLMProphetNetForCausalLM""",
          """XLMProphetNetForConditionalGeneration""",
          """XLMProphetNetModel""",
          """XLMProphetNetPreTrainedModel""",
      ]


if TYPE_CHECKING:
      from .configuration_xlm_prophetnet import XLM_PROPHETNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMProphetNetConfig

      try:
            if not is_sentencepiece_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .tokenization_xlm_prophetnet import XLMProphetNetTokenizer

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_xlm_prophetnet import (
                XLM_PROPHETNET_PRETRAINED_MODEL_ARCHIVE_LIST,
                XLMProphetNetDecoder,
                XLMProphetNetEncoder,
                XLMProphetNetForCausalLM,
                XLMProphetNetForConditionalGeneration,
                XLMProphetNetModel,
                XLMProphetNetPreTrainedModel,
            )

else:
      import sys

      A__	:      List[str]				=						_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)






