






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       ,A__       ,A__=3       ,A__=32       ,A__=3       ,A__=10       ,A__=[10, 20, 30, 40]       ,A__=[1, 1, 2, 1]       ,A__=True       ,A__=True       ,A__="relu"       ,A__=3       ,A__=None       ,):
						_A	:				Union[str, Any]   =      parent
						_A	:				Any   =      batch_size
						_A	:				Dict   =      image_size
						_A	:				Optional[int]   =      num_channels
						_A	:				List[Any]   =      embeddings_size
						_A	:				Any   =      hidden_sizes
						_A	:				Union[str, Any]   =      depths
						_A	:				str   =      is_training
						_A	:				str   =      use_labels
						_A	:				Any   =      hidden_act
						_A	:				Any   =      num_labels
						_A	:				Any   =      scope
						_A	:				List[str]   =      len(A__		)







		def  A__      (					self		):
						_A	:				Union[str, Any]   =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

						_A	:				Tuple   =      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       ,A__       ,A__       ,A__		):
						_A	:				List[Any]   =      TFRegNetModel(config=A__		)
						_A	:				str   =      model(A__       ,training=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 // 32, self.image_size // 32)       ,)







		def  A__      (					self       ,A__       ,A__       ,A__		):
						_A	:				Tuple   =      self.num_labels
						_A	:				List[Any]   =      TFRegNetForImageClassification(A__		)
						_A	:				List[str]   =      model(A__       ,labels=A__       ,training=A__		)
						self.parent.assertEqual(result.logits.shape       ,(self.batch_size, self.num_labels)		)







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






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

		__snake_case      :       Union[str, Any]     =   False
		__snake_case      :       Optional[int]     =   False
		__snake_case      :       Tuple     =   False
		__snake_case      :       int     =   False
		__snake_case      :       List[str]     =   False







		def  A__      (					self		):
						_A	:				List[Any]   =      TFRegNetModelTester(self		)
						_A	:				List[str]   =      ConfigTester(self       ,config_class=A__       ,has_text_modality=A__		)







		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		):
						_A  ,				_A	:				Any   =      self.model_tester.prepare_config_and_inputs_for_common()

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

										_A	:				Optional[Any]   =      ['''pixel_values''']
										self.assertListEqual(arg_names[:1]       ,A__		)







		def  A__      (					self		):
						_A	:				int   =      self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*A__		)







		def  A__      (					self		):
						def check_hidden_states_output(A__       ,A__       ,A__		):
										_A	:				List[str]   =      model_class(A__		)
										_A	:				Dict   =      model(**self._prepare_for_class(A__       ,A__		)       ,training=A__		)

										_A	:				Dict   =      outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

										_A	:				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]       ,)

						_A  ,				_A	:				Tuple   =      self.model_tester.prepare_config_and_inputs_for_common()
						_A	:				str   =      ['''basic''', '''bottleneck''']
						for model_class in self.all_model_classes:
										for layer_type in layers_type:
														_A	:				str   =      layer_type
														_A	:				List[Any]   =      True
														check_hidden_states_output(A__       ,A__       ,A__		)

														# check that output_hidden_states also work using config
														del inputs_dict["output_hidden_states"]
														_A	:				List[Any]   =      True

														check_hidden_states_output(A__       ,A__       ,A__		)







		def  A__      (					self		):
						_A  ,				_A	:				Union[str, Any]   =      self.model_tester.prepare_config_and_inputs_for_common()

						def check_equivalence(A__       ,A__       ,A__       ,A__={}		):
										_A	:				str   =      model(A__       ,return_dict=A__       ,**A__		)
										_A	:				List[Any]   =      model(A__       ,return_dict=A__       ,**A__		).to_tuple()

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

														recursive_check(A__       ,A__		)

						for model_class in self.all_model_classes:
										_A	:				int   =      model_class(A__		)

										_A	:				Optional[int]   =      self._prepare_for_class(A__       ,A__		)
										_A	:				Dict   =      self._prepare_for_class(A__       ,A__		)
										check_equivalence(A__       ,A__       ,A__		)

										_A	:				int   =      self._prepare_for_class(A__       ,A__       ,return_labels=A__		)
										_A	:				List[Any]   =      self._prepare_for_class(A__       ,A__       ,return_labels=A__		)
										check_equivalence(A__       ,A__       ,A__		)

										_A	:				Tuple   =      self._prepare_for_class(A__       ,A__		)
										_A	:				Any   =      self._prepare_for_class(A__       ,A__		)
										check_equivalence(A__       ,A__       ,A__       ,{'''output_hidden_states''': True}		)

										_A	:				Any   =      self._prepare_for_class(A__       ,A__       ,return_labels=A__		)
										_A	:				Union[str, Any]   =      self._prepare_for_class(A__       ,A__       ,return_labels=A__		)
										check_equivalence(A__       ,A__       ,A__       ,{'''output_hidden_states''': True}		)







		def  A__      (					self		):
						_A	:				str   =      self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*A__		)







		@slow
		def  A__      (					self		):
						for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										_A	:				Tuple   =      TFRegNetModel.from_pretrained(A__		)
										self.assertIsNotNone(A__		)



def  a__ ()		-> str:
				_A	:				Any   =      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
				return image






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







		@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		):
						_A	:				str   =      TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)

						_A	:				Optional[int]   =      self.default_image_processor
						_A	:				List[str]   =      prepare_img()
						_A	:				Optional[Any]   =      image_processor(images=A__       ,return_tensors='''tf'''		)

						# forward pass
						_A	:				Any   =      model(**A__       ,training=A__		)

						# verify the logits
						_A	:				List[str]   =      tf.TensorShape((1, 1000)		)
						self.assertEqual(outputs.logits.shape       ,A__		)

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

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











from ...configuration_utils import PretrainedConfig
from ...utils import logging


_UpperCamelCase			:	Optional[int]								=logging.get_logger(__name__)

_UpperCamelCase			:	Tuple								={
    'google/canine-s': 'https://huggingface.co/google/canine-s/resolve/main/config.json',
    # See all CANINE models at https://huggingface.co/models?filter=canine
}






class 						UpperCAmelCase__ (							__snake_case							):
		__snake_case      :       Any     =   "canine"







		def __init__(					self       ,A__=768       ,A__=12       ,A__=12       ,A__=3072       ,A__="gelu"       ,A__=0.1       ,A__=0.1       ,A__=16384       ,A__=16       ,A__=0.02       ,A__=1E-12       ,A__=0       ,A__=0xE_000       ,A__=0xE_001       ,A__=4       ,A__=4       ,A__=8       ,A__=16384       ,A__=128       ,**A__       ,):
						super().__init__(pad_token_id=A__       ,bos_token_id=A__       ,eos_token_id=A__       ,**A__		)

						_A	:				int   =      max_position_embeddings
						_A	:				Dict   =      hidden_size
						_A	:				List[str]   =      num_hidden_layers
						_A	:				Optional[Any]   =      num_attention_heads
						_A	:				Optional[Any]   =      intermediate_size
						_A	:				Optional[Any]   =      hidden_act
						_A	:				str   =      hidden_dropout_prob
						_A	:				Optional[int]   =      attention_probs_dropout_prob
						_A	:				Union[str, Any]   =      initializer_range
						_A	:				Dict   =      type_vocab_size
						_A	:				Optional[Any]   =      layer_norm_eps

						# Character config:
						_A	:				Union[str, Any]   =      downsampling_rate
						_A	:				List[str]   =      upsampling_kernel_size
						_A	:				str   =      num_hash_functions
						_A	:				Optional[Any]   =      num_hash_buckets
						_A	:				Optional[Any]   =      local_transformer_stride



