
"""simple docstring"""





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 A_	(unittest.TestCase      ):




  '''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				,   ):

     """simple docstring"""
     UpperCAmelCase_					:					Union[str, Any]			     =    parent
     UpperCAmelCase_					:					Tuple			     =    batch_size
     UpperCAmelCase_					:					List[Any]			     =    image_size
     UpperCAmelCase_					:					Optional[int]			     =    num_channels
     UpperCAmelCase_					:					Union[str, Any]			     =    embeddings_size
     UpperCAmelCase_					:					str			     =    hidden_sizes
     UpperCAmelCase_					:					List[Any]			     =    depths
     UpperCAmelCase_					:					List[str]			     =    is_training
     UpperCAmelCase_					:					Optional[int]			     =    use_labels
     UpperCAmelCase_					:					List[str]			     =    hidden_act
     UpperCAmelCase_					:					Tuple			     =    num_labels
     UpperCAmelCase_					:					Dict			     =    scope
     UpperCAmelCase_					:					Tuple			     =    len(lowercase_  )







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_					:					int			     =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

     UpperCAmelCase_					:					List[str]			     =    self.get_config()

     return config, pixel_values







  def        UpperCamelCase__					(		self  ):

     """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        UpperCamelCase__					(		self				,   lowercase_				,   lowercase_  ):

     """simple docstring"""
     UpperCAmelCase_					:					Union[str, Any]			     =    FlaxRegNetModel(config=lowercase_  )
     UpperCAmelCase_					:					List[str]			     =    model(lowercase_  )

     # Output shape (b, c, h, w)
     self.parent.assertEqual(
         result.last_hidden_state.shape				,   (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)				,   )







  def        UpperCamelCase__					(		self				,   lowercase_				,   lowercase_  ):

     """simple docstring"""
     UpperCAmelCase_					:					int			     =    self.num_labels
     UpperCAmelCase_					:					str			     =    FlaxRegNetForImageClassification(config=lowercase_  )
     UpperCAmelCase_					:					Tuple			     =    model(lowercase_  )
     self.parent.assertEqual(result.logits.shape				,   (self.batch_size, self.num_labels)  )







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_					:					str			     =    self.prepare_config_and_inputs()
     UpperCAmelCase_     ,   UpperCAmelCase_					:					List[Any]			     =    config_and_inputs
     UpperCAmelCase_					:					List[Any]			     =    {"pixel_values": pixel_values}
     return config, inputs_dict




@require_flax
class A_	(lowercase__				,unittest.TestCase      ):




  '''simple docstring'''
  SCREAMING_SNAKE_CASE__			:						Any       =		(FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

  SCREAMING_SNAKE_CASE__			:						Any       =		False
  SCREAMING_SNAKE_CASE__			:						int       =		False
  SCREAMING_SNAKE_CASE__			:						Tuple       =		False







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_					:					List[str]			     =    FlaxRegNetModelTester(self  )
     UpperCAmelCase_					:					str			     =    ConfigTester(self				,   config_class=lowercase_				,   has_text_modality=lowercase_  )







  def        UpperCamelCase__					(		self  ):

     """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        UpperCamelCase__					(		self  ):

     """simple docstring"""
     return







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_					:					List[str]			     =    self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowercase_  )







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_					:					Dict			     =    self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*lowercase_  )







  @unittest.skip(reason="RegNet does not use inputs_embeds"  )
  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     pass







  @unittest.skip(reason="RegNet does not support input and output embeddings"  )
  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     pass







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_     ,   UpperCAmelCase_					:					List[str]			     =    self.model_tester.prepare_config_and_inputs_for_common()

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

        UpperCAmelCase_					:					List[Any]			     =    ["pixel_values"]
        self.assertListEqual(arg_names[:1]				,   lowercase_  )







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     def check_hidden_states_output(lowercase_				,   lowercase_				,   lowercase_  ):
        UpperCAmelCase_					:					Optional[int]			     =    model_class(lowercase_  )

        UpperCAmelCase_					:					List[str]			     =    model(**self._prepare_for_class(lowercase_				,   lowercase_  )  )

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

        UpperCAmelCase_					:					int			     =    self.model_tester.num_stages
        self.assertEqual(len(lowercase_  )				,   expected_num_stages + 1  )

     UpperCAmelCase_     ,   UpperCAmelCase_					:					Optional[int]			     =    self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        UpperCAmelCase_					:					int			     =    True
        check_hidden_states_output(lowercase_				,   lowercase_				,   lowercase_  )

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

        check_hidden_states_output(lowercase_				,   lowercase_				,   lowercase_  )







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_     ,   UpperCAmelCase_					:					List[Any]			     =    self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        with self.subTest(model_class.__name__  ):
           UpperCAmelCase_					:					Optional[int]			     =    self._prepare_for_class(lowercase_				,   lowercase_  )
           UpperCAmelCase_					:					Dict			     =    model_class(lowercase_  )

           @jax.jit
           def model_jitted(lowercase_				,   **lowercase_  ):
              return model(pixel_values=lowercase_				,   **lowercase_  )

           with self.subTest("JIT Enabled"  ):
              UpperCAmelCase_					:					Dict			     =    model_jitted(**lowercase_  ).to_tuple()

           with self.subTest("JIT Disabled"  ):
              with jax.disable_jit():
                 UpperCAmelCase_					:					int			     =    model_jitted(**lowercase_  ).to_tuple()

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







def 	__a     (		):
   UpperCAmelCase_					:					Optional[int]			     =    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  )
   return image


@require_flax
class A_	(unittest.TestCase      ):




  '''simple docstring'''







  @cached_property
  def        UpperCamelCase__					(		self  ):

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







  @slow
  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_					:					str			     =    FlaxRegNetForImageClassification.from_pretrained("facebook/regnet-y-040"  )

     UpperCAmelCase_					:					str			     =    self.default_image_processor
     UpperCAmelCase_					:					Optional[Any]			     =    prepare_img()
     UpperCAmelCase_					:					Union[str, Any]			     =    image_processor(images=lowercase_				,   return_tensors="np"  )

     UpperCAmelCase_					:					str			     =    model(**lowercase_  )

     # verify the logits
     UpperCAmelCase_					:					Tuple			     =    (1, 1000)
     self.assertEqual(outputs.logits.shape				,   lowercase_  )

     UpperCAmelCase_					:					List[str]			     =    jnp.array([-0.41_80, -1.50_51, -3.48_36]  )

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







"""simple docstring"""
import random
import unittest

import torch

from diffusers import IFImgaImgSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin
@skip_mps
class 							_UpperCAmelCase							( a		,a		,unittest.TestCase      ):





     '''simple docstring'''



     a__									=IFImgaImgSuperResolutionPipeline
     a__									=TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''width''', '''height'''}
     a__									=TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''original_image'''}      )
     a__									=PipelineTesterMixin.required_optional_params - {'''latents'''}





     def  __lowerCAmelCase	(					self		)							->					List[str]:
         return self._get_superresolution_dummy_components()





     def  __lowerCAmelCase	(					self       ,	A       ,	A=0		)							->					Union[str, Any]:
         if str(A		).startswith('''mps'''		):
             _UpperCAmelCase							:  Any											=    torch.manual_seed(A		)
         else:
             _UpperCAmelCase							:  int											=    torch.Generator(device=A		).manual_seed(A		)

         _UpperCAmelCase							:  str											=    floats_tensor((1, 3, 3_2, 3_2)       ,	rng=random.Random(A		)		).to(A		)
         _UpperCAmelCase							:  Dict											=    floats_tensor((1, 3, 1_6, 1_6)       ,	rng=random.Random(A		)		).to(A		)

         _UpperCAmelCase							:  List[Any]											=    {
             '''prompt''': '''A painting of a squirrel eating a burger''',
             '''image''': image,
             '''original_image''': original_image,
             '''generator''': generator,
             '''num_inference_steps''': 2,
             '''output_type''': '''numpy''',
         }

         return inputs





     @unittest.skipIf(
         torch_device != '''cuda''' or not is_xformers_available()       ,	reason='''XFormers attention is only available with CUDA and `xformers` installed'''       ,	)
     def  __lowerCAmelCase	(					self		)							->					List[Any]:
         self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3		)





     def  __lowerCAmelCase	(					self		)							->					List[str]:
         self._test_save_load_optional_components()





     @unittest.skipIf(torch_device != '''cuda'''       ,	reason='''float16 requires CUDA'''		)
     def  __lowerCAmelCase	(					self		)							->					Optional[Any]:
         # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
         super().test_save_load_floataa(expected_max_diff=1E-1		)





     def  __lowerCAmelCase	(					self		)							->					int:
         self._test_attention_slicing_forward_pass(expected_max_diff=1E-2		)





     def  __lowerCAmelCase	(					self		)							->					Union[str, Any]:
         self._test_save_load_local()





     def  __lowerCAmelCase	(					self		)							->					Union[str, Any]:
         self._test_inference_batch_single_identical(
             expected_max_diff=1E-2       ,	)


