






"""simple docstring"""





import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, 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 torch import nn

  from transformers import RegNetForImageClassification, RegNetModel
  from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor


class      _lowercase :


      def __init__(    self				:	List[str]							,   a				:	List[Any]							,   a				:	int=3							,   a				:	List[Any]=3_2							,   a				:	Union[str, Any]=3							,   a				:	Union[str, Any]=1_0							,   a				:	int=[1_0, 2_0, 3_0, 4_0]							,   a				:	int=[1, 1, 2, 1]							,   a				:	int=True							,   a				:	str=True							,   a				:	Union[str, Any]="relu"							,   a				:	Union[str, Any]=3							,   a				:	Any=None							,   ):





            """simple docstring"""







            __snake_case      :    Optional[Any]  			=parent
            __snake_case      :    Optional[Any]  			=batch_size
            __snake_case      :    Dict  			=image_size
            __snake_case      :    int  			=num_channels
            __snake_case      :    int  			=embeddings_size
            __snake_case      :    Optional[Any]  			=hidden_sizes
            __snake_case      :    Tuple  			=depths
            __snake_case      :    List[Any]  			=is_training
            __snake_case      :    int  			=use_labels
            __snake_case      :    Any  			=hidden_act
            __snake_case      :    Any  			=num_labels
            __snake_case      :    List[Any]  			=scope
            __snake_case      :    Dict  			=len(a						)


      def _UpperCamelCase						(    self				:	Optional[int]						):





            """simple docstring"""







            __snake_case      :    Optional[int]  			=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

            __snake_case      :    Optional[int]  			=self.get_config()

            return config, pixel_values, labels


      def _UpperCamelCase						(    self				:	Any						):





            """simple docstring"""







            return RegNetConfig(
                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							,   )


      def _UpperCamelCase						(    self				:	List[str]							,   a				:	str							,   a				:	Any							,   a				:	Tuple						):





            """simple docstring"""







            __snake_case      :    Any  			=RegNetModel(config=a						)
            model.to(a						)
            model.eval()
            __snake_case      :    Tuple  			=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 // 3_2, self.image_size // 3_2)							,   )


      def _UpperCamelCase						(    self				:	Optional[int]							,   a				:	int							,   a				:	List[Any]							,   a				:	Optional[Any]						):





            """simple docstring"""







            __snake_case      :    List[str]  			=self.num_labels
            __snake_case      :    Union[str, Any]  			=RegNetForImageClassification(a						)
            model.to(a						)
            model.eval()
            __snake_case      :    str  			=model(a							,   labels=a						)
            self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.num_labels)						)







      def _UpperCamelCase						(    self				:	Tuple						):





            """simple docstring"""







            __snake_case      :    Optional[Any]  			=self.prepare_config_and_inputs()
            __snake_case			,				__snake_case			,				__snake_case      :    Tuple  			=config_and_inputs
            __snake_case      :    int  			={'''pixel_values''': pixel_values}
            return config, inputs_dict



@require_torch
class      _lowercase (     lowerCAmelCase		,  lowerCAmelCase		,  unittest.TestCase						):
      _a   :     Optional[int]								=   (RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
      _a   :     Any								=   (
          {"""feature-extraction""": RegNetModel, """image-classification""": RegNetForImageClassification}
          if is_torch_available()
          else {}
      )

      _a   :     List[Any]								=   False
      _a   :     Optional[Any]								=   False
      _a   :     str								=   False
      _a   :     Optional[int]								=   False


      def _UpperCamelCase						(    self				:	str						):





            """simple docstring"""







            __snake_case      :    List[Any]  			=RegNetModelTester(self						)
            __snake_case      :    int  			=ConfigTester(self							,   config_class=a							,   has_text_modality=a						)


      def _UpperCamelCase						(    self				:	List[str]						):





            """simple docstring"""







            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				:	Any						):





            """simple docstring"""







            return


      @unittest.skip(reason='''RegNet does not use inputs_embeds'''						)
      def _UpperCamelCase						(    self				:	List[str]						):





            """simple docstring"""







            pass


      @unittest.skip(reason='''RegNet does not support input and output embeddings'''						)
      def _UpperCamelCase						(    self				:	str						):





            """simple docstring"""







            pass


      def _UpperCamelCase						(    self				:	Any						):





            """simple docstring"""







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

            for model_class in self.all_model_classes:
                  __snake_case      :    Dict  			=model_class(a						)
                  __snake_case      :    Optional[int]  			=inspect.signature(model.forward						)
                  # signature.parameters is an OrderedDict => so arg_names order is deterministic
                  __snake_case      :    Optional[int]  			=[*signature.parameters.keys()]

                  __snake_case      :    int  			=['''pixel_values''']
                  self.assertListEqual(arg_names[:1]							,   a						)


      def _UpperCamelCase						(    self				:	str						):





            """simple docstring"""







            __snake_case      :    List[Any]  			=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*a						)


      def _UpperCamelCase						(    self				:	List[Any]						):





            """simple docstring"""







            __snake_case			,				__snake_case      :    Dict  			=self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                  __snake_case      :    List[str]  			=model_class(config=a						)
                  for name, module in model.named_modules():
                        if isinstance(a							,   (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 _UpperCamelCase						(    self				:	int						):





            """simple docstring"""







            def check_hidden_states_output(a				:	List[Any]							,   a				:	List[Any]							,   a				:	List[Any]						):
                  __snake_case      :    Any  			=model_class(a						)
                  model.to(a						)
                  model.eval()

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

                  __snake_case      :    List[Any]  			=outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                  __snake_case      :    Optional[Any]  			=self.model_tester.num_stages
                  self.assertEqual(len(a						)							,   expected_num_stages + 1						)

                  # RegNet'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 // 2, self.model_tester.image_size // 2]							,   )

            __snake_case			,				__snake_case      :    int  			=self.model_tester.prepare_config_and_inputs_for_common()
            __snake_case      :    List[str]  			=['''basic''', '''bottleneck''']
            for model_class in self.all_model_classes:
                  for layer_type in layers_type:
                        __snake_case      :    Dict  			=layer_type
                        __snake_case      :    str  			=True
                        check_hidden_states_output(a							,   a							,   a						)

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

                        check_hidden_states_output(a							,   a							,   a						)


      def _UpperCamelCase						(    self				:	Optional[Any]						):





            """simple docstring"""







            __snake_case      :    Dict  			=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*a						)







      @slow
      def _UpperCamelCase						(    self				:	Optional[Any]						):





            """simple docstring"""







            for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  __snake_case      :    Dict  			=RegNetModel.from_pretrained(a						)
                  self.assertIsNotNone(a						)



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


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


      @cached_property
      def _UpperCamelCase						(    self				:	Union[str, Any]						):





            """simple docstring"""







            return (
                AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)
                if is_vision_available()
                else None
            )







      @slow
      def _UpperCamelCase						(    self				:	Union[str, Any]						):





            """simple docstring"""







            __snake_case      :    Union[str, Any]  			=RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						).to(a						)

            __snake_case      :    Tuple  			=self.default_image_processor
            __snake_case      :    Union[str, Any]  			=prepare_img()
            __snake_case      :    Tuple  			=image_processor(images=a							,   return_tensors='''pt'''						).to(a						)

            # forward pass
            with torch.no_grad():
                  __snake_case      :    Union[str, Any]  			=model(**a						)

            # verify the logits
            __snake_case      :    List[str]  			=torch.Size((1, 1_0_0_0)						)
            self.assertEqual(outputs.logits.shape							,   a						)

            __snake_case      :    Any  			=torch.tensor([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6]						).to(a						)

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










"""simple docstring"""





import unittest

import numpy as np

from transformers.testing_utils import is_flaky, require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image

    from transformers import DonutImageProcessor


class      _lowercase (     unittest.TestCase						):


      def __init__(    self				:	List[Any]							,   a				:	int							,   a				:	Dict=7							,   a				:	int=3							,   a				:	int=1_8							,   a				:	Dict=3_0							,   a				:	Dict=4_0_0							,   a				:	Optional[Any]=True							,   a				:	Dict=None							,   a				:	int=True							,   a				:	Dict=False							,   a				:	int=True							,   a				:	str=True							,   a				:	List[str]=[0.5, 0.5, 0.5]							,   a				:	Optional[Any]=[0.5, 0.5, 0.5]							,   ):





            """simple docstring"""







            __snake_case      :    List[Any]  			=parent
            __snake_case      :    List[Any]  			=batch_size
            __snake_case      :    str  			=num_channels
            __snake_case      :    Dict  			=image_size
            __snake_case      :    str  			=min_resolution
            __snake_case      :    Tuple  			=max_resolution
            __snake_case      :    str  			=do_resize
            __snake_case      :    Any  			=size if size is not None else {'''height''': 1_8, '''width''': 2_0}
            __snake_case      :    List[Any]  			=do_thumbnail
            __snake_case      :    Tuple  			=do_align_axis
            __snake_case      :    Any  			=do_pad
            __snake_case      :    Dict  			=do_normalize
            __snake_case      :    List[Any]  			=image_mean
            __snake_case      :    Any  			=image_std







      def _UpperCamelCase						(    self				:	str						):





            """simple docstring"""







            return {
                "do_resize": self.do_resize,
                "size": self.size,
                "do_thumbnail": self.do_thumbnail,
                "do_align_long_axis": self.do_align_axis,
                "do_pad": self.do_pad,
                "do_normalize": self.do_normalize,
                "image_mean": self.image_mean,
                "image_std": self.image_std,
            }



@require_torch
@require_vision
class      _lowercase (     lowerCAmelCase		,  unittest.TestCase						):
      _a   :     str								=   DonutImageProcessor if is_vision_available() else None


      def _UpperCamelCase						(    self				:	Optional[int]						):





            """simple docstring"""







            __snake_case      :    Optional[Any]  			=DonutImageProcessingTester(self						)


      @property
      def _UpperCamelCase						(    self				:	Optional[int]						):





            """simple docstring"""







            return self.image_processor_tester.prepare_image_processor_dict()


      def _UpperCamelCase						(    self				:	List[str]						):





            """simple docstring"""







            __snake_case      :    Optional[Any]  			=self.image_processing_class(**self.image_processor_dict						)
            self.assertTrue(hasattr(a							,   '''do_resize'''						)						)
            self.assertTrue(hasattr(a							,   '''size'''						)						)
            self.assertTrue(hasattr(a							,   '''do_thumbnail'''						)						)
            self.assertTrue(hasattr(a							,   '''do_align_long_axis'''						)						)
            self.assertTrue(hasattr(a							,   '''do_pad'''						)						)
            self.assertTrue(hasattr(a							,   '''do_normalize'''						)						)
            self.assertTrue(hasattr(a							,   '''image_mean'''						)						)
            self.assertTrue(hasattr(a							,   '''image_std'''						)						)


      def _UpperCamelCase						(    self				:	Tuple						):





            """simple docstring"""







            __snake_case      :    Dict  			=self.image_processing_class.from_dict(self.image_processor_dict						)
            self.assertEqual(image_processor.size							,   {'''height''': 1_8, '''width''': 2_0}						)

            __snake_case      :    List[Any]  			=self.image_processing_class.from_dict(self.image_processor_dict							,   size=4_2						)
            self.assertEqual(image_processor.size							,   {'''height''': 4_2, '''width''': 4_2}						)

            # Previous config had dimensions in (width, height) order
            __snake_case      :    Tuple  			=self.image_processing_class.from_dict(self.image_processor_dict							,   size=(4_2, 8_4)						)
            self.assertEqual(image_processor.size							,   {'''height''': 8_4, '''width''': 4_2}						)


      def _UpperCamelCase						(    self				:	Any						):





            """simple docstring"""







            pass


      @is_flaky()
      def _UpperCamelCase						(    self				:	Union[str, Any]						):





            """simple docstring"""







            __snake_case      :    List[Any]  			=self.image_processing_class(**self.image_processor_dict						)
            # create random PIL images
            __snake_case      :    List[Any]  			=prepare_image_inputs(self.image_processor_tester							,   equal_resolution=a						)
            for image in image_inputs:
                  self.assertIsInstance(a							,   Image.Image						)

            # Test not batched input
            __snake_case      :    str  			=image_processing(image_inputs[0]							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    1,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )

            # Test batched
            __snake_case      :    Optional[int]  			=image_processing(a							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )


      @is_flaky()
      def _UpperCamelCase						(    self				:	Tuple						):





            """simple docstring"""







            __snake_case      :    Tuple  			=self.image_processing_class(**self.image_processor_dict						)
            # create random numpy tensors
            __snake_case      :    Optional[int]  			=prepare_image_inputs(self.image_processor_tester							,   equal_resolution=a							,   numpify=a						)
            for image in image_inputs:
                  self.assertIsInstance(a							,   np.ndarray						)

            # Test not batched input
            __snake_case      :    List[Any]  			=image_processing(image_inputs[0]							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    1,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )

            # Test batched
            __snake_case      :    int  			=image_processing(a							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )







      @is_flaky()
      def _UpperCamelCase						(    self				:	List[str]						):





            """simple docstring"""







            __snake_case      :    Dict  			=self.image_processing_class(**self.image_processor_dict						)
            # create random PyTorch tensors
            __snake_case      :    Dict  			=prepare_image_inputs(self.image_processor_tester							,   equal_resolution=a							,   torchify=a						)
            for image in image_inputs:
                  self.assertIsInstance(a							,   torch.Tensor						)

            # Test not batched input
            __snake_case      :    Dict  			=image_processing(image_inputs[0]							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    1,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )

            # Test batched
            __snake_case      :    Optional[int]  			=image_processing(a							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )


