





'''simple docstring'''






from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
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 TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor




class 					UpperCAmelCase	:




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




      def 							lowercase__       (     self     :					int    )							-> int:
            _lowerCAmelCase					=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

            _lowerCAmelCase					=				None
            if self.use_labels:
                  _lowerCAmelCase					=				ids_tensor([self.batch_size]     ,     self.num_labels    )

            _lowerCAmelCase					=				self.get_config()
            return config, pixel_values, labels




      def 							lowercase__       (     self     :					int    )							-> int:
            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 							lowercase__       (     self     :					Dict     ,     __snake_case     :					List[str]     ,     __snake_case     :					Union[str, Any]     ,     __snake_case     :					List[str]    )							-> Any:
            _lowerCAmelCase					=				TFRegNetModel(config=__snake_case    )
            _lowerCAmelCase					=				model(__snake_case     ,     training=__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     :					Union[str, Any]     ,     __snake_case     :					int     ,     __snake_case     :					Optional[Any]     ,     __snake_case     :					Dict    )							-> List[Any]:
            _lowerCAmelCase					=				self.num_labels
            _lowerCAmelCase					=				TFRegNetForImageClassification(__snake_case    )
            _lowerCAmelCase					=				model(__snake_case     ,     labels=__snake_case     ,     training=__snake_case    )
            self.parent.assertEqual(result.logits.shape     ,     (self.batch_size, self.num_labels)    )




      def 							lowercase__       (     self     :					str    )							-> Optional[Any]:
            _lowerCAmelCase					=				self.prepare_config_and_inputs()
            _lowerCAmelCase	,				_lowerCAmelCase	,				_lowerCAmelCase					=				config_and_inputs
            _lowerCAmelCase					=				{"""pixel_values""": pixel_values}
            return config, inputs_dict




@require_tf
class 					UpperCAmelCase	(     snake_case_				,						snake_case_				,						unittest.TestCase  ):
      _lowercase:     Union[str, Any]			=  (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
      _lowercase:     Tuple			=  (
          {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification}
          if is_tf_available()
          else {}
      )

      _lowercase:     Optional[Any]			=  False
      _lowercase:     int			=  False
      _lowercase:     str			=  False
      _lowercase:     Any			=  False
      _lowercase:     Optional[Any]			=  False




      def 							lowercase__       (     self     :					Any    )							-> Tuple:
            _lowerCAmelCase					=				TFRegNetModelTester(self    )
            _lowerCAmelCase					=				ConfigTester(self     ,     config_class=__snake_case     ,     has_text_modality=__snake_case    )




      def 							lowercase__       (     self     :					Any    )							-> List[str]:
            return




      @unittest.skip(reason="""RegNet does not use inputs_embeds"""    )
      def 							lowercase__       (     self     :					Tuple    )							-> Any:
            pass




      @unittest.skipIf(
          not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""    )    ) == 0     ,     reason="""TF does not support backprop for grouped convolutions on CPU."""     ,     )
      @slow
      def 							lowercase__       (     self     :					Any    )							-> Optional[int]:
            super().test_keras_fit()




      @unittest.skip(reason="""RegNet does not support input and output embeddings"""    )
      def 							lowercase__       (     self     :					Dict    )							-> Union[str, Any]:
            pass




      def 							lowercase__       (     self     :					Tuple    )							-> Any:
            _lowerCAmelCase	,				_lowerCAmelCase					=				self.model_tester.prepare_config_and_inputs_for_common()

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

                  _lowerCAmelCase					=				["""pixel_values"""]
                  self.assertListEqual(arg_names[:1]     ,     __snake_case    )




      def 							lowercase__       (     self     :					Optional[Any]    )							-> Optional[Any]:
            _lowerCAmelCase					=				self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*__snake_case    )




      def 							lowercase__       (     self     :					Optional[Any]    )							-> List[str]:
            def check_hidden_states_output(__snake_case     :					Dict     ,     __snake_case     :					Tuple     ,     __snake_case     :					Tuple    ):
                  _lowerCAmelCase					=				model_class(__snake_case    )
                  _lowerCAmelCase					=				model(**self._prepare_for_class(__snake_case     ,     __snake_case    )     ,     training=__snake_case    )

                  _lowerCAmelCase					=				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                  _lowerCAmelCase					=				self.model_tester.num_stages
                  self.assertEqual(len(__snake_case    )     ,     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]     ,     )

            _lowerCAmelCase	,				_lowerCAmelCase					=				self.model_tester.prepare_config_and_inputs_for_common()
            _lowerCAmelCase					=				["""basic""", """bottleneck"""]
            for model_class in self.all_model_classes:
                  for layer_type in layers_type:
                        _lowerCAmelCase					=				layer_type
                        _lowerCAmelCase					=				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"]
                        _lowerCAmelCase					=				True

                        check_hidden_states_output(__snake_case     ,     __snake_case     ,     __snake_case    )




      def 							lowercase__       (     self     :					Optional[Any]    )							-> int:
            _lowerCAmelCase	,				_lowerCAmelCase					=				self.model_tester.prepare_config_and_inputs_for_common()

            def check_equivalence(__snake_case     :					Optional[int]     ,     __snake_case     :					str     ,     __snake_case     :					Tuple     ,     __snake_case     :					Union[str, Any]={}    ):
                  _lowerCAmelCase					=				model(__snake_case     ,     return_dict=__snake_case     ,     **__snake_case    )
                  _lowerCAmelCase					=				model(__snake_case     ,     return_dict=__snake_case     ,     **__snake_case    ).to_tuple()

                  def recursive_check(__snake_case     :					Dict     ,     __snake_case     :					int    ):
                        if isinstance(__snake_case     ,     (List, Tuple)    ):
                              for tuple_iterable_value, dict_iterable_value in zip(__snake_case     ,     __snake_case    ):
                                    recursive_check(__snake_case     ,     __snake_case    )
                        elif tuple_object is None:
                              return
                        else:
                              self.assertTrue(
                                  all(tf.equal(__snake_case     ,     __snake_case    )    )     ,     msg=(
                                      """Tuple and dict output are not equal. Difference:"""
                                      f" {tf.math.reduce_max(tf.abs(tuple_object - dict_object    )    )}"
                                  )     ,     )

                        recursive_check(__snake_case     ,     __snake_case    )

            for model_class in self.all_model_classes:
                  _lowerCAmelCase					=				model_class(__snake_case    )

                  _lowerCAmelCase					=				self._prepare_for_class(__snake_case     ,     __snake_case    )
                  _lowerCAmelCase					=				self._prepare_for_class(__snake_case     ,     __snake_case    )
                  check_equivalence(__snake_case     ,     __snake_case     ,     __snake_case    )

                  _lowerCAmelCase					=				self._prepare_for_class(__snake_case     ,     __snake_case     ,     return_labels=__snake_case    )
                  _lowerCAmelCase					=				self._prepare_for_class(__snake_case     ,     __snake_case     ,     return_labels=__snake_case    )
                  check_equivalence(__snake_case     ,     __snake_case     ,     __snake_case    )

                  _lowerCAmelCase					=				self._prepare_for_class(__snake_case     ,     __snake_case    )
                  _lowerCAmelCase					=				self._prepare_for_class(__snake_case     ,     __snake_case    )
                  check_equivalence(__snake_case     ,     __snake_case     ,     __snake_case     ,     {"""output_hidden_states""": True}    )

                  _lowerCAmelCase					=				self._prepare_for_class(__snake_case     ,     __snake_case     ,     return_labels=__snake_case    )
                  _lowerCAmelCase					=				self._prepare_for_class(__snake_case     ,     __snake_case     ,     return_labels=__snake_case    )
                  check_equivalence(__snake_case     ,     __snake_case     ,     __snake_case     ,     {"""output_hidden_states""": True}    )




      def 							lowercase__       (     self     :					Union[str, Any]    )							-> str:
            _lowerCAmelCase					=				self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*__snake_case    )




      @slow
      def 							lowercase__       (     self     :					Tuple    )							-> Dict:
            for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  _lowerCAmelCase					=				TFRegNetModel.from_pretrained(__snake_case    )
                  self.assertIsNotNone(__snake_case    )




def   UpperCamelCase__ (						):





      """simple docstring"""


      _lowerCAmelCase					=				Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    )
      return image





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




      @cached_property
      def 							lowercase__       (     self     :					Union[str, Any]    )							-> Any:
            return (
                AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )
                if is_vision_available()
                else None
            )




      @slow
      def 							lowercase__       (     self     :					Optional[int]    )							-> Optional[int]:
            _lowerCAmelCase					=				TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )

            _lowerCAmelCase					=				self.default_image_processor
            _lowerCAmelCase					=				prepare_img()
            _lowerCAmelCase					=				image_processor(images=__snake_case     ,     return_tensors="""tf"""    )

            # forward pass
            _lowerCAmelCase					=				model(**__snake_case     ,     training=__snake_case    )

            # verify the logits
            _lowerCAmelCase					=				tf.TensorShape((1, 10_00)    )
            self.assertEqual(outputs.logits.shape     ,     __snake_case    )

            _lowerCAmelCase					=				tf.constant([-0.41_80, -1.50_51, -3.48_36]    )

            tf.debugging.assert_near(outputs.logits[0, :3]     ,     __snake_case     ,     atol=1E-4    )













'''simple docstring'''






from typing import Callable, Optional

from .. import Features
from ..packaged_modules.generator.generator import Generator
from .abc import AbstractDatasetInputStream




class 					UpperCAmelCase	(     snake_case_  ):




      def __init__(     self     :					Union[str, Any]     ,     __snake_case     :					Callable     ,     __snake_case     :					Optional[Features] = None     ,     __snake_case     :					str = None     ,     __snake_case     :					bool = False     ,     __snake_case     :					bool = False     ,     __snake_case     :					Optional[dict] = None     ,     __snake_case     :					Optional[int] = None     ,     **__snake_case     :					Optional[Any]     ,     )							-> Union[str, Any]:
            super().__init__(
                features=__snake_case     ,     cache_dir=__snake_case     ,     keep_in_memory=__snake_case     ,     streaming=__snake_case     ,     num_proc=__snake_case     ,     **__snake_case     ,     )
            _lowerCAmelCase					=				Generator(
                cache_dir=__snake_case     ,     features=__snake_case     ,     generator=__snake_case     ,     gen_kwargs=__snake_case     ,     **__snake_case     ,     )




      def 							lowercase__       (     self     :					str    )							-> Dict:
            # Build iterable dataset
            if self.streaming:
                  _lowerCAmelCase					=				self.builder.as_streaming_dataset(split="""train"""    )
            # Build regular (map-style) dataset
            else:
                  _lowerCAmelCase					=				None
                  _lowerCAmelCase					=				None
                  _lowerCAmelCase					=				None
                  _lowerCAmelCase					=				None

                  self.builder.download_and_prepare(
                      download_config=__snake_case     ,     download_mode=__snake_case     ,     verification_mode=__snake_case     ,     base_path=__snake_case     ,     num_proc=self.num_proc     ,     )
                  _lowerCAmelCase					=				self.builder.as_dataset(
                      split="""train"""     ,     verification_mode=__snake_case     ,     in_memory=self.keep_in_memory    )
            return dataset






