

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       snake_case_  :







			'''simple docstring'''

			def __init__(	self					:							str				,  _UpperCamelCase					:							Optional[Any]				,  _UpperCamelCase					:							Optional[Any]=3				,  _UpperCamelCase					:							int=3_2				,  _UpperCamelCase					:							Tuple=3				,  _UpperCamelCase					:							List[str]=1_0				,  _UpperCamelCase					:							Tuple=[1_0, 2_0, 3_0, 4_0]				,  _UpperCamelCase					:							Optional[Any]=[1, 1, 2, 1]				,  _UpperCamelCase					:							Any=True				,  _UpperCamelCase					:							List[Any]=True				,  _UpperCamelCase					:							Optional[Any]="relu"				,  _UpperCamelCase					:							Any=3				,  _UpperCamelCase					:							Dict=None				,  ) ->str:
									snake_case_  =      parent
									snake_case_  =      batch_size
									snake_case_  =      image_size
									snake_case_  =      num_channels
									snake_case_  =      embeddings_size
									snake_case_  =      hidden_sizes
									snake_case_  =      depths
									snake_case_  =      is_training
									snake_case_  =      use_labels
									snake_case_  =      hidden_act
									snake_case_  =      num_labels
									snake_case_  =      scope
									snake_case_  =      len(_UpperCamelCase				)







			def 							snake_case__(	self					:							Tuple				) ->Any:
									snake_case_  =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

									snake_case_  =      self.get_config()

									return config, pixel_values, labels







			def 							snake_case__(	self					:							Optional[int]				) ->Optional[Any]:
									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 							snake_case__(	self					:							Any				,  _UpperCamelCase					:							Optional[int]				,  _UpperCamelCase					:							Optional[int]				,  _UpperCamelCase					:							Optional[int]				) ->Union[str, Any]:
									snake_case_  =      RegNetModel(config=_UpperCamelCase				)
									model.to(_UpperCamelCase				)
									model.eval()
									snake_case_  =      model(_UpperCamelCase				)
									# 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 							snake_case__(	self					:							Optional[int]				,  _UpperCamelCase					:							int				,  _UpperCamelCase					:							Dict				,  _UpperCamelCase					:							List[str]				) ->List[str]:
									snake_case_  =      self.num_labels
									snake_case_  =      RegNetForImageClassification(_UpperCamelCase				)
									model.to(_UpperCamelCase				)
									model.eval()
									snake_case_  =      model(_UpperCamelCase				,  labels=_UpperCamelCase				)
									self.parent.assertEqual(result.logits.shape				,  (self.batch_size, self.num_labels)				)







			def 							snake_case__(	self					:							Tuple				) ->int:
									snake_case_  =      self.prepare_config_and_inputs()
									snake_case_,       snake_case_,       snake_case_  =      config_and_inputs
									snake_case_  =      {'''pixel_values''': pixel_values}
									return config, inputs_dict






@require_torch
class       snake_case_  (						__A      ,			__A      ,			unittest.TestCase   ):







			'''simple docstring'''

			SCREAMING_SNAKE_CASE	:  Any		     =							(RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
			SCREAMING_SNAKE_CASE	:  Tuple		     =							(
			    {"feature-extraction": RegNetModel, "image-classification": RegNetForImageClassification}
			    if is_torch_available()
			    else {}
			)

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







			def 							snake_case__(	self					:							str				) ->Dict:
									snake_case_  =      RegNetModelTester(self				)
									snake_case_  =      ConfigTester(self				,  config_class=_UpperCamelCase				,  has_text_modality=_UpperCamelCase				)







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







			@unittest.skip(reason='''RegNet does not use inputs_embeds'''				)
			def 							snake_case__(	self					:							Optional[Any]				) ->str:
									pass







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







			def 							snake_case__(	self					:							Any				) ->Optional[Any]:
									snake_case_,       snake_case_  =      self.model_tester.prepare_config_and_inputs_for_common()

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

															snake_case_  =      ['''pixel_values''']
															self.assertListEqual(arg_names[:1]				,  _UpperCamelCase				)







			def 							snake_case__(	self					:							Dict				) ->Any:
									snake_case_  =      self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_UpperCamelCase				)







			def 							snake_case__(	self					:							List[str]				) ->Tuple:
									snake_case_,       snake_case_  =      self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															snake_case_  =      model_class(config=_UpperCamelCase				)
															for name, module in model.named_modules():
																					if isinstance(_UpperCamelCase				,  (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 							snake_case__(	self					:							int				) ->Optional[int]:
									def check_hidden_states_output(_UpperCamelCase					:							Optional[int]				,  _UpperCamelCase					:							Union[str, Any]				,  _UpperCamelCase					:							Optional[int]				):
															snake_case_  =      model_class(_UpperCamelCase				)
															model.to(_UpperCamelCase				)
															model.eval()

															with torch.no_grad():
																					snake_case_  =      model(**self._prepare_for_class(_UpperCamelCase				,  _UpperCamelCase				)				)

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

															snake_case_  =      self.model_tester.num_stages
															self.assertEqual(len(_UpperCamelCase				)				,  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_  =      self.model_tester.prepare_config_and_inputs_for_common()
									snake_case_  =      ['''basic''', '''bottleneck''']
									for model_class in self.all_model_classes:
															for layer_type in layers_type:
																					snake_case_  =      layer_type
																					snake_case_  =      True
																					check_hidden_states_output(_UpperCamelCase				,  _UpperCamelCase				,  _UpperCamelCase				)

																					# check that output_hidden_states also work using config
																					del inputs_dict["output_hidden_states"]
																					snake_case_  =      True

																					check_hidden_states_output(_UpperCamelCase				,  _UpperCamelCase				,  _UpperCamelCase				)







			def 							snake_case__(	self					:							str				) ->Any:
									snake_case_  =      self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*_UpperCamelCase				)







			@slow
			def 							snake_case__(	self					:							Dict				) ->str:
									for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															snake_case_  =      RegNetModel.from_pretrained(_UpperCamelCase				)
															self.assertIsNotNone(_UpperCamelCase				)






def     __SCREAMING_SNAKE_CASE   ():
						snake_case_  =      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''			)
						return image





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







			'''simple docstring'''

			@cached_property
			def 							snake_case__(	self					:							Optional[int]				) ->Tuple:
									return (
									    AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)
									    if is_vision_available()
									    else None
									)







			@slow
			def 							snake_case__(	self					:							Dict				) ->str:
									snake_case_  =      RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				).to(_UpperCamelCase				)

									snake_case_  =      self.default_image_processor
									snake_case_  =      prepare_img()
									snake_case_  =      image_processor(images=_UpperCamelCase				,  return_tensors='''pt'''				).to(_UpperCamelCase				)

									# forward pass
									with torch.no_grad():
															snake_case_  =      model(**_UpperCamelCase				)

									# verify the logits
									snake_case_  =      torch.Size((1, 1_0_0_0)				)
									self.assertEqual(outputs.logits.shape				,  _UpperCamelCase				)

									snake_case_  =      torch.tensor([-0.4180, -1.5051, -3.4836]				).to(_UpperCamelCase				)

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





'''simple docstring'''







# Lint as: python3
# pylint: enable=line-too-long
# pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position

lowerCAmelCase_     						=				'''2.13.1'''

import platform

import pyarrow
from packaging import version


if version.parse(platform.python_version()) < version.parse('''3.7'''):
    raise ImportWarning(
        '''To use `datasets`, Python>=3.7 is required, and the current version of Python doesn\'t match this condition.'''
    )

if version.parse(pyarrow.__version__).major < 8:
    raise ImportWarning(
        '''To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn\'t match this condition.\n'''
        '''If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`.'''
    )

del platform
del pyarrow
del version

from .arrow_dataset import Dataset
from .arrow_reader import ReadInstruction
from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder
from .combine import concatenate_datasets, interleave_datasets
from .dataset_dict import DatasetDict, IterableDatasetDict
from .download import *
from .features import *
from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled
from .info import DatasetInfo, MetricInfo
from .inspect import (
    get_dataset_config_info,
    get_dataset_config_names,
    get_dataset_infos,
    get_dataset_split_names,
    inspect_dataset,
    inspect_metric,
    list_datasets,
    list_metrics,
)
from .iterable_dataset import IterableDataset
from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric
from .metric import Metric
from .splits import (
    NamedSplit,
    NamedSplitAll,
    Split,
    SplitBase,
    SplitDict,
    SplitGenerator,
    SplitInfo,
    SubSplitInfo,
    percent,
)
from .tasks import *
from .utils import *
from .utils import logging


# deprecated modules
from datasets import arrow_dataset as _arrow_dataset  # isort:skip
from datasets import utils as _utils  # isort:skip
from datasets.utils import download_manager as _deprecated_download_manager  # isort:skip

lowerCAmelCase_     						=				concatenate_datasets
lowerCAmelCase_     						=				DownloadConfig
lowerCAmelCase_     						=				DownloadManager
lowerCAmelCase_     						=				DownloadMode
lowerCAmelCase_     						=				DownloadConfig
lowerCAmelCase_     						=				DownloadMode
lowerCAmelCase_     						=				DownloadManager

del _arrow_dataset, _utils, _deprecated_download_manager


