import inspect
import unittest

from transformers import RegNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
   import jax
   import jax.numpy as jnp

   from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel

if is_vision_available():
   from PIL import Image

   from transformers import AutoImageProcessor





class 		_lowercase						(					unittest.TestCase       ):

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

  """simple docstring"""





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

 def 						SCREAMING_SNAKE_CASE__   ( self	:							int			)   ->						Union[str, Any]:

  """simple docstring"""





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

  UpperCamelCase_					:						int =					self.get_config()

  return config, pixel_values

 def 						SCREAMING_SNAKE_CASE__   ( self	:							Optional[int]			)   ->						Optional[int]:

  """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   ,      image_size=self.image_size   ,      )

 def 						SCREAMING_SNAKE_CASE__   ( self	:							str   ,      snake_case	:							int   ,      snake_case	:							Tuple			)   ->						str:

  """simple docstring"""





  UpperCamelCase_					:						int =					FlaxRegNetModel(config=__lowerCamelCase			)
  UpperCamelCase_					:						int =					model(__lowerCamelCase			)

  # Output shape (b, c, h, w)
  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 						SCREAMING_SNAKE_CASE__   ( self	:							Union[str, Any]   ,      snake_case	:							Any   ,      snake_case	:							str			)   ->						Union[str, Any]:

  """simple docstring"""





  UpperCamelCase_					:						str =					self.num_labels
  UpperCamelCase_					:						Tuple =					FlaxRegNetForImageClassification(config=__lowerCamelCase			)
  UpperCamelCase_					:						Union[str, Any] =					model(__lowerCamelCase			)
  self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, self.num_labels)			)


 def 						SCREAMING_SNAKE_CASE__   ( self	:							Any			)   ->						Dict:

  """simple docstring"""





  UpperCamelCase_					:						str =					self.prepare_config_and_inputs()
  UpperCamelCase_					:						Tuple =					config_and_inputs
  UpperCamelCase_					:						int =					{"""pixel_values""": pixel_values}
  return config, inputs_dict





@require_flax
class 		_lowercase						(					_a						,      unittest.TestCase       ):
 lowercase				     =   (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

 lowercase				     =   False
 lowercase				     =   False
 lowercase				     =   False

 def 						SCREAMING_SNAKE_CASE__   ( self	:							Any			)   ->						Dict:

  """simple docstring"""





  UpperCamelCase_					:						Any =					FlaxRegNetModelTester(self			)
  UpperCamelCase_					:						Tuple =					ConfigTester(self   ,      config_class=__lowerCamelCase   ,      has_text_modality=__lowerCamelCase			)

 def 						SCREAMING_SNAKE_CASE__   ( self	:							str			)   ->						Optional[int]:

  """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 						SCREAMING_SNAKE_CASE__   ( self	:							List[Any]			)   ->						Tuple:

  """simple docstring"""





  return

 def 						SCREAMING_SNAKE_CASE__   ( self	:							int			)   ->						List[str]:

  """simple docstring"""





  UpperCamelCase_					:						Any =					self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_model(*__lowerCamelCase			)

 def 						SCREAMING_SNAKE_CASE__   ( self	:							List[Any]			)   ->						Tuple:

  """simple docstring"""





  UpperCamelCase_					:						Optional[Any] =					self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase			)

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

  """simple docstring"""





  pass

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

  """simple docstring"""





  pass

 def 						SCREAMING_SNAKE_CASE__   ( self	:							str			)   ->						List[str]:

  """simple docstring"""





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

  for model_class in self.all_model_classes:
   UpperCamelCase_					:						Dict =					model_class(__lowerCamelCase			)
   UpperCamelCase_					:						Dict =					inspect.signature(model.__call__			)
   # signature.parameters is an OrderedDict => so arg_names order is deterministic
   UpperCamelCase_					:						Any =					[*signature.parameters.keys()]

   UpperCamelCase_					:						Dict =					["""pixel_values"""]
   self.assertListEqual(arg_names[:1]   ,      __lowerCamelCase			)

 def 						SCREAMING_SNAKE_CASE__   ( self	:							List[str]			)   ->						Optional[Any]:

  """simple docstring"""





  def check_hidden_states_output(snake_case	:							Any   ,      snake_case	:							Tuple   ,      snake_case	:							Tuple			):
   UpperCamelCase_					:						Union[str, Any] =					model_class(__lowerCamelCase			)

   UpperCamelCase_					:						str =					model(**self._prepare_for_class(__lowerCamelCase   ,      __lowerCamelCase			)			)

   UpperCamelCase_					:						str =					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

   UpperCamelCase_					:						str =					self.model_tester.num_stages
   self.assertEqual(len(__lowerCamelCase			)   ,      expected_num_stages + 1			)

  UpperCamelCase_					:						Any =					self.model_tester.prepare_config_and_inputs_for_common()

  for model_class in self.all_model_classes:
   UpperCamelCase_					:						Dict =					True
   check_hidden_states_output(__lowerCamelCase   ,      __lowerCamelCase   ,      __lowerCamelCase			)

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

   check_hidden_states_output(__lowerCamelCase   ,      __lowerCamelCase   ,      __lowerCamelCase			)


 def 						SCREAMING_SNAKE_CASE__   ( self	:							Optional[Any]			)   ->						str:

  """simple docstring"""





  UpperCamelCase_					:						Tuple =					self.model_tester.prepare_config_and_inputs_for_common()

  for model_class in self.all_model_classes:
   with self.subTest(model_class.__name__			):
    UpperCamelCase_					:						Tuple =					self._prepare_for_class(__lowerCamelCase   ,      __lowerCamelCase			)
    UpperCamelCase_					:						Optional[int] =					model_class(__lowerCamelCase			)

    @jax.jit
    def model_jitted(snake_case	:							Optional[Any]   ,      **snake_case	:							Optional[int]			):
     return model(pixel_values=__lowerCamelCase   ,      **__lowerCamelCase			)

    with self.subTest('JIT Enabled'			):
     UpperCamelCase_					:						Dict =					model_jitted(**__lowerCamelCase			).to_tuple()

    with self.subTest('JIT Disabled'			):
     with jax.disable_jit():
      UpperCamelCase_					:						Optional[Any] =					model_jitted(**__lowerCamelCase			).to_tuple()

    self.assertEqual(len(__lowerCamelCase			)   ,      len(__lowerCamelCase			)			)
    for jitted_output, output in zip(__lowerCamelCase   ,      __lowerCamelCase			):
     self.assertEqual(jitted_output.shape   ,      output.shape			)





def    __lowercase     (						):
 UpperCamelCase_					:						Any =					Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
 return image






@require_flax
class 		_lowercase						(					unittest.TestCase       ):

 @cached_property
 def 						SCREAMING_SNAKE_CASE__   ( self	:							Optional[Any]			)   ->						Optional[Any]:

  """simple docstring"""





  return AutoImageProcessor.from_pretrained('facebook/regnet-y-040'			) if is_vision_available() else None


 @slow
 def 						SCREAMING_SNAKE_CASE__   ( self	:							Any			)   ->						int:

  """simple docstring"""





  UpperCamelCase_					:						Any =					FlaxRegNetForImageClassification.from_pretrained('facebook/regnet-y-040'			)

  UpperCamelCase_					:						Optional[int] =					self.default_image_processor
  UpperCamelCase_					:						Dict =					prepare_img()
  UpperCamelCase_					:						Union[str, Any] =					image_processor(images=__lowerCamelCase   ,      return_tensors='np'			)

  UpperCamelCase_					:						List[Any] =					model(**__lowerCamelCase			)

  # verify the logits
  UpperCamelCase_					:						int =					(1, 1_0_0_0)
  self.assertEqual(outputs.logits.shape   ,      __lowerCamelCase			)

  UpperCamelCase_					:						Union[str, Any] =					jnp.array([-0.4180, -1.5051, -3.4836]			)

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











import unittest

import numpy as np

from transformers.testing_utils import 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 ViTImageProcessor

class     _SCREAMING_SNAKE_CASE       (			unittest.TestCase      ):





	def __init__(		self				:					List[str] ,  __lowerCamelCase				:					Optional[Any] ,  __lowerCamelCase				:					Any=13 ,  __lowerCamelCase				:					Dict=3 ,  __lowerCamelCase				:					int=224 ,  __lowerCamelCase				:					Any=30 ,  __lowerCamelCase				:					Tuple=400 ,  __lowerCamelCase				:					int=True ,  __lowerCamelCase				:					List[str]=None ,  __lowerCamelCase				:					Any=True ,  __lowerCamelCase				:					Dict=[0.5, 0.5, 0.5] ,  __lowerCamelCase				:					List[Any]=[0.5, 0.5, 0.5] ,  ):
		UpperCamelCase     :List[Any]          =	size if size is not None else {"""height""": 18, """width""": 18}
		UpperCamelCase     :str          =	parent
		UpperCamelCase     :Optional[int]          =	batch_size
		UpperCamelCase     :Dict          =	num_channels
		UpperCamelCase     :str          =	image_size
		UpperCamelCase     :Dict          =	min_resolution
		UpperCamelCase     :str          =	max_resolution
		UpperCamelCase     :Union[str, Any]          =	do_resize
		UpperCamelCase     :Optional[Any]          =	size
		UpperCamelCase     :Any          =	do_normalize
		UpperCamelCase     :Optional[Any]          =	image_mean
		UpperCamelCase     :Tuple          =	image_std





	def 						_A (		self				:					int	):
		return {
		    "image_mean": self.image_mean,
		    "image_std": self.image_std,
		    "do_normalize": self.do_normalize,
		    "do_resize": self.do_resize,
		    "size": self.size,
		}

@require_torch
@require_vision
class     _SCREAMING_SNAKE_CASE       (			_a		,   unittest.TestCase      ):
	snake_case__							:     List[Any]     	=  ViTImageProcessor if is_vision_available() else None





	def 						_A (		self				:					str	):
		UpperCamelCase     :Tuple          =	EfficientFormerImageProcessorTester(self	)





	@property
	def 						_A (		self				:					List[str]	):
		return self.image_proc_tester.prepare_image_processor_dict()





	def 						_A (		self				:					int	):
		UpperCamelCase     :List[Any]          =	self.image_processing_class(**self.image_processor_dict	)
		self.assertTrue(hasattr(__lowerCamelCase ,  """image_mean"""	)	)
		self.assertTrue(hasattr(__lowerCamelCase ,  """image_std"""	)	)
		self.assertTrue(hasattr(__lowerCamelCase ,  """do_normalize"""	)	)
		self.assertTrue(hasattr(__lowerCamelCase ,  """do_resize"""	)	)
		self.assertTrue(hasattr(__lowerCamelCase ,  """size"""	)	)





	def 						_A (		self				:					Optional[int]	):
		pass





	def 						_A (		self				:					str	):
		# Initialize image_processor
		UpperCamelCase     :Union[str, Any]          =	self.image_processing_class(**self.image_processor_dict	)
		# create random PIL images
		UpperCamelCase     :Union[str, Any]          =	prepare_image_inputs(self.image_proc_tester ,  equal_resolution=__lowerCamelCase	)
		for image in image_inputs:
			self.assertIsInstance(__lowerCamelCase ,  Image.Image	)

		# Test not batched input
		UpperCamelCase     :List[str]          =	image_processor(image_inputs[0] ,  return_tensors="""pt"""	).pixel_values
		self.assertEqual(
		    encoded_images.shape ,  (
		        1,
		        self.image_proc_tester.num_channels,
		        self.image_proc_tester.size["""height"""],
		        self.image_proc_tester.size["""width"""],
		    ) ,  )

		# Test batched
		UpperCamelCase     :List[Any]          =	image_processor(__lowerCamelCase ,  return_tensors="""pt"""	).pixel_values
		self.assertEqual(
		    encoded_images.shape ,  (
		        self.image_proc_tester.batch_size,
		        self.image_proc_tester.num_channels,
		        self.image_proc_tester.size["""height"""],
		        self.image_proc_tester.size["""width"""],
		    ) ,  )





	def 						_A (		self				:					Union[str, Any]	):
		# Initialize image_processor
		UpperCamelCase     :Optional[int]          =	self.image_processing_class(**self.image_processor_dict	)
		# create random numpy tensors
		UpperCamelCase     :List[Any]          =	prepare_image_inputs(self.image_proc_tester ,  equal_resolution=__lowerCamelCase ,  numpify=__lowerCamelCase	)
		for image in image_inputs:
			self.assertIsInstance(__lowerCamelCase ,  np.ndarray	)

		# Test not batched input
		UpperCamelCase     :Dict          =	image_processor(image_inputs[0] ,  return_tensors="""pt"""	).pixel_values
		self.assertEqual(
		    encoded_images.shape ,  (
		        1,
		        self.image_proc_tester.num_channels,
		        self.image_proc_tester.size["""height"""],
		        self.image_proc_tester.size["""width"""],
		    ) ,  )

		# Test batched
		UpperCamelCase     :Tuple          =	image_processor(__lowerCamelCase ,  return_tensors="""pt"""	).pixel_values
		self.assertEqual(
		    encoded_images.shape ,  (
		        self.image_proc_tester.batch_size,
		        self.image_proc_tester.num_channels,
		        self.image_proc_tester.size["""height"""],
		        self.image_proc_tester.size["""width"""],
		    ) ,  )





	def 						_A (		self				:					List[Any]	):
		# Initialize image_processor
		UpperCamelCase     :List[str]          =	self.image_processing_class(**self.image_processor_dict	)
		# create random PyTorch tensors
		UpperCamelCase     :Any          =	prepare_image_inputs(self.image_proc_tester ,  equal_resolution=__lowerCamelCase ,  torchify=__lowerCamelCase	)
		for image in image_inputs:
			self.assertIsInstance(__lowerCamelCase ,  torch.Tensor	)

		# Test not batched input
		UpperCamelCase     :List[Any]          =	image_processor(image_inputs[0] ,  return_tensors="""pt"""	).pixel_values
		self.assertEqual(
		    encoded_images.shape ,  (
		        1,
		        self.image_proc_tester.num_channels,
		        self.image_proc_tester.size["""height"""],
		        self.image_proc_tester.size["""width"""],
		    ) ,  )

		# Test batched
		UpperCamelCase     :str          =	image_processor(__lowerCamelCase ,  return_tensors="""pt"""	).pixel_values
		self.assertEqual(
		    encoded_images.shape ,  (
		        self.image_proc_tester.batch_size,
		        self.image_proc_tester.num_channels,
		        self.image_proc_tester.size["""height"""],
		        self.image_proc_tester.size["""width"""],
		    ) ,  )
