




"""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 lowerCAmelCase__	:






			'''simple docstring'''



			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     :			List[str]    =    parent
							_lowerCamelCase     :			Dict    =    batch_size
							_lowerCamelCase     :			Optional[Any]    =    image_size
							_lowerCamelCase     :			int    =    num_channels
							_lowerCamelCase     :			int    =    embeddings_size
							_lowerCamelCase     :			Optional[Any]    =    hidden_sizes
							_lowerCamelCase     :			Tuple    =    depths
							_lowerCamelCase     :			Optional[Any]    =    is_training
							_lowerCamelCase     :			Optional[Any]    =    use_labels
							_lowerCamelCase     :			Tuple    =    hidden_act
							_lowerCamelCase     :			Tuple    =    num_labels
							_lowerCamelCase     :			List[str]    =    scope
							_lowerCamelCase     :			Union[str, Any]    =    len(lowercase  )
			def 					A_    (  self  ):
							_lowerCamelCase     :			int    =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

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

							_lowerCamelCase     :			Any    =    self.get_config()
							return config, pixel_values, labels
			def 					A_    (  self  ):
							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 					A_    (  self  ,      lowercase  ,      lowercase  ,      lowercase  ):
							_lowerCamelCase     :			Optional[int]    =    TFRegNetModel(config=lowercase  )
							_lowerCamelCase     :			Any    =    model(lowercase  ,      training=lowercase  )
							# 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 					A_    (  self  ,      lowercase  ,      lowercase  ,      lowercase  ):
							_lowerCamelCase     :			str    =    self.num_labels
							_lowerCamelCase     :			int    =    TFRegNetForImageClassification(lowercase  )
							_lowerCamelCase     :			List[str]    =    model(lowercase  ,      labels=lowercase  ,      training=lowercase  )
							self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.num_labels)  )






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






@require_tf
class lowerCAmelCase__	(     lowercase,	lowercase,	unittest.TestCase						):






			'''simple docstring'''



			lowerCamelCase__      =			(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
			lowerCamelCase__      =			(
			    {"""feature-extraction""": TFRegNetModel, """image-classification""": TFRegNetForImageClassification}
			    if is_tf_available()
			    else {}
			)

			lowerCamelCase__      =			False
			lowerCamelCase__      =			False
			lowerCamelCase__      =			False
			lowerCamelCase__      =			False
			lowerCamelCase__      =			False
			def 					A_    (  self  ):
							_lowerCamelCase     :			Union[str, Any]    =    TFRegNetModelTester(self  )
							_lowerCamelCase     :			Union[str, Any]    =    ConfigTester(self  ,      config_class=lowercase  ,      has_text_modality=lowercase  )
			def 					A_    (  self  ):
							return
			@unittest.skip(reason='RegNet does not use inputs_embeds'  )
			def 					A_    (  self  ):
							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 					A_    (  self  ):
							super().test_keras_fit()
			@unittest.skip(reason='RegNet does not support input and output embeddings'  )
			def 					A_    (  self  ):
							pass
			def 					A_    (  self  ):
							_lowerCamelCase, _lowerCamelCase     :			Tuple    =    self.model_tester.prepare_config_and_inputs_for_common()

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

											_lowerCamelCase     :			int    =    ['pixel_values']
											self.assertListEqual(arg_names[:1]  ,      lowercase  )
			def 					A_    (  self  ):
							_lowerCamelCase     :			Dict    =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowercase  )
			def 					A_    (  self  ):
							def check_hidden_states_output(lowercase  ,      lowercase  ,      lowercase  ):
											_lowerCamelCase     :			Optional[Any]    =    model_class(lowercase  )
											_lowerCamelCase     :			List[Any]    =    model(**self._prepare_for_class(lowercase  ,      lowercase  )  ,      training=lowercase  )

											_lowerCamelCase     :			Tuple    =    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

											_lowerCamelCase     :			str    =    self.model_tester.num_stages
											self.assertEqual(len(lowercase  )  ,      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     :			Any    =    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     :			Tuple    =    layer_type
															_lowerCamelCase     :			int    =    True
															check_hidden_states_output(lowercase  ,      lowercase  ,      lowercase  )

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

															check_hidden_states_output(lowercase  ,      lowercase  ,      lowercase  )
			def 					A_    (  self  ):
							_lowerCamelCase, _lowerCamelCase     :			int    =    self.model_tester.prepare_config_and_inputs_for_common()

							def check_equivalence(lowercase  ,      lowercase  ,      lowercase  ,      lowercase={}  ):
											_lowerCamelCase     :			Optional[Any]    =    model(lowercase  ,      return_dict=lowercase  ,      **lowercase  )
											_lowerCamelCase     :			int    =    model(lowercase  ,      return_dict=lowercase  ,      **lowercase  ).to_tuple()

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

															recursive_check(lowercase  ,      lowercase  )

							for model_class in self.all_model_classes:
											_lowerCamelCase     :			Dict    =    model_class(lowercase  )

											_lowerCamelCase     :			Any    =    self._prepare_for_class(lowercase  ,      lowercase  )
											_lowerCamelCase     :			List[Any]    =    self._prepare_for_class(lowercase  ,      lowercase  )
											check_equivalence(lowercase  ,      lowercase  ,      lowercase  )

											_lowerCamelCase     :			Any    =    self._prepare_for_class(lowercase  ,      lowercase  ,      return_labels=lowercase  )
											_lowerCamelCase     :			int    =    self._prepare_for_class(lowercase  ,      lowercase  ,      return_labels=lowercase  )
											check_equivalence(lowercase  ,      lowercase  ,      lowercase  )

											_lowerCamelCase     :			int    =    self._prepare_for_class(lowercase  ,      lowercase  )
											_lowerCamelCase     :			Union[str, Any]    =    self._prepare_for_class(lowercase  ,      lowercase  )
											check_equivalence(lowercase  ,      lowercase  ,      lowercase  ,      {'output_hidden_states': True}  )

											_lowerCamelCase     :			Optional[Any]    =    self._prepare_for_class(lowercase  ,      lowercase  ,      return_labels=lowercase  )
											_lowerCamelCase     :			List[str]    =    self._prepare_for_class(lowercase  ,      lowercase  ,      return_labels=lowercase  )
											check_equivalence(lowercase  ,      lowercase  ,      lowercase  ,      {'output_hidden_states': True}  )
			def 					A_    (  self  ):
							_lowerCamelCase     :			Tuple    =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*lowercase  )






			@slow
			def 					A_    (  self  ):
							for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											_lowerCamelCase     :			Dict    =    TFRegNetModel.from_pretrained(lowercase  )
											self.assertIsNotNone(lowercase  )







def      _snake_case			(				):
				_lowerCamelCase     :			Optional[Any]    =    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'		)
				return image






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






			'''simple docstring'''



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






			@slow
			def 					A_    (  self  ):
							_lowerCamelCase     :			Optional[Any]    =    TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )

							_lowerCamelCase     :			Optional[int]    =    self.default_image_processor
							_lowerCamelCase     :			Optional[int]    =    prepare_img()
							_lowerCamelCase     :			Optional[Any]    =    image_processor(images=lowercase  ,      return_tensors='tf'  )

							# forward pass
							_lowerCamelCase     :			Dict    =    model(**lowercase  ,      training=lowercase  )

							# verify the logits
							_lowerCamelCase     :			Any    =    tf.TensorShape((1, 1000)  )
							self.assertEqual(outputs.logits.shape  ,      lowercase  )

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

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





'''simple docstring'''







from typing import List, Optional, TypeVar

from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets
from .dataset_dict import DatasetDict, IterableDatasetDict
from .info import DatasetInfo
from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasets
from .splits import NamedSplit
from .utils import logging
from .utils.py_utils import Literal


A     =logging.get_logger(__name__)


A     =TypeVar('DatasetType', Dataset, IterableDataset)





def 						snake_case_							(_a	:							List[DatasetType]    ,   _a	:							Optional[List[float]] = None    ,   _a	:							Optional[int] = None    ,   _a	:							Optional[DatasetInfo] = None    ,   _a	:							Optional[NamedSplit] = None    ,   _a	:							Literal["first_exhausted", "all_exhausted"] = "first_exhausted"    ,   ):
    from .arrow_dataset import Dataset
    from .iterable_dataset import IterableDataset

    if not datasets:
        raise ValueError('''Unable to interleave an empty list of datasets.'''     )
    for i, dataset in enumerate(_a     ):
        if not isinstance(_a    ,   (Dataset, IterableDataset)     ):
            if isinstance(_a    ,   (DatasetDict, IterableDatasetDict)     ):
                if not dataset:
                    raise ValueError(
                        F"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} "
                        '''is an empty dataset dictionary.'''     )
                raise ValueError(
                    F"Dataset at position {i} has at least one split: {list(_a     )}\n"
                    F"Please pick one to interleave with the other datasets, for example: dataset['{next(iter(_a     )     )}']"     )
            raise ValueError(
                F"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(_a     ).__name__}."     )
        if i == 0:
            UpperCAmelCase       ,     UpperCAmelCase			       =		(
                (Dataset, IterableDataset) if isinstance(_a    ,   _a     ) else (IterableDataset, Dataset)
            )
        elif not isinstance(_a    ,   _a     ):
            raise ValueError(
                F"Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects."     )
    if stopping_strategy not in ["first_exhausted", "all_exhausted"]:
        raise ValueError(F"{stopping_strategy} is not supported. Please enter a valid stopping_strategy."     )
    if dataset_type is Dataset:
        return _interleave_map_style_datasets(
            _a    ,   _a    ,   _a    ,   info=_a    ,   split=_a    ,   stopping_strategy=_a     )
    else:
        return _interleave_iterable_datasets(
            _a    ,   _a    ,   _a    ,   info=_a    ,   split=_a    ,   stopping_strategy=_a     )







def 						snake_case_							(_a	:							List[DatasetType]    ,   _a	:							Optional[DatasetInfo] = None    ,   _a	:							Optional[NamedSplit] = None    ,   _a	:							int = 0    ,   ):

    if not dsets:
        raise ValueError('''Unable to concatenate an empty list of datasets.'''     )
    for i, dataset in enumerate(_a     ):
        if not isinstance(_a    ,   (Dataset, IterableDataset)     ):
            if isinstance(_a    ,   (DatasetDict, IterableDatasetDict)     ):
                if not dataset:
                    raise ValueError(
                        F"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} "
                        '''is an empty dataset dictionary.'''     )
                raise ValueError(
                    F"Dataset at position {i} has at least one split: {list(_a     )}\n"
                    F"Please pick one to interleave with the other datasets, for example: dataset['{next(iter(_a     )     )}']"     )
            raise ValueError(
                F"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(_a     ).__name__}."     )
        if i == 0:
            UpperCAmelCase       ,     UpperCAmelCase			       =		(
                (Dataset, IterableDataset) if isinstance(_a    ,   _a     ) else (IterableDataset, Dataset)
            )
        elif not isinstance(_a    ,   _a     ):
            raise ValueError(
                F"Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects."     )
    if dataset_type is Dataset:
        return _concatenate_map_style_datasets(_a    ,   info=_a    ,   split=_a    ,   axis=_a     )
    else:
        return _concatenate_iterable_datasets(_a    ,   info=_a    ,   split=_a    ,   axis=_a     )




