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



    def __init__(self   :   Optional[int]       ,      __a   :   List[str]       ,      __a   :   Union[str, Any]=3       ,      __a   :   List[str]=32       ,      __a   :   Optional[int]=3       ,      __a   :   Union[str, Any]=10       ,      __a   :   int=[10, 20, 30, 40]       ,      __a   :   Union[str, Any]=[1, 1, 2, 1]       ,      __a   :   Tuple=True       ,      __a   :   List[Any]=True       ,      __a   :   Optional[int]="relu"       ,      __a   :   Union[str, Any]=3       ,      __a   :   Optional[int]=None       ,      ):
         UpperCAmelCase_	   =       parent
         UpperCAmelCase_	   =       batch_size
         UpperCAmelCase_	   =       image_size
         UpperCAmelCase_	   =       num_channels
         UpperCAmelCase_	   =       embeddings_size
         UpperCAmelCase_	   =       hidden_sizes
         UpperCAmelCase_	   =       depths
         UpperCAmelCase_	   =       is_training
         UpperCAmelCase_	   =       use_labels
         UpperCAmelCase_	   =       hidden_act
         UpperCAmelCase_	   =       num_labels
         UpperCAmelCase_	   =       scope
         UpperCAmelCase_	   =       len(__a			)



    def  _lowercase						(self   :   Tuple			):
         UpperCAmelCase_	   =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

         UpperCAmelCase_	   =       self.get_config()

         return config, pixel_values



    def  _lowercase						(self   :   Union[str, 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       ,      image_size=self.image_size       ,      )



    def  _lowercase						(self   :   Union[str, Any]       ,      __a   :   Union[str, Any]       ,      __a   :   Dict			):
         UpperCAmelCase_	   =       FlaxRegNetModel(config=__a			)
         UpperCAmelCase_	   =       model(__a			)

         # 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  _lowercase						(self   :   Tuple       ,      __a   :   int       ,      __a   :   Any			):
         UpperCAmelCase_	   =       self.num_labels
         UpperCAmelCase_	   =       FlaxRegNetForImageClassification(config=__a			)
         UpperCAmelCase_	   =       model(__a			)
         self.parent.assertEqual(result.logits.shape       ,      (self.batch_size, self.num_labels)			)






    def  _lowercase						(self   :   Optional[int]			):
         UpperCAmelCase_	   =       self.prepare_config_and_inputs()
         UpperCAmelCase_   ,			UpperCAmelCase_	   =       config_and_inputs
         UpperCAmelCase_	   =       {"pixel_values": pixel_values}
         return config, inputs_dict




@require_flax
class 	__A				(			UpperCamelCase__		,     unittest.TestCase     ):
    a__	:						str	       =  (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

    a__	:						int	       =  False
    a__	:						int	       =  False
    a__	:						Optional[int]	       =  False



    def  _lowercase						(self   :   Dict			):
         UpperCAmelCase_	   =       FlaxRegNetModelTester(self			)
         UpperCAmelCase_	   =       ConfigTester(self       ,      config_class=__a       ,      has_text_modality=__a			)



    def  _lowercase						(self   :   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  _lowercase						(self   :   Tuple			):
         return



    def  _lowercase						(self   :   int			):
         UpperCAmelCase_	   =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__a			)



    def  _lowercase						(self   :   List[Any]			):
         UpperCAmelCase_	   =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__a			)



    @unittest.skip(reason="RegNet does not use inputs_embeds"			)
    def  _lowercase						(self   :   Optional[int]			):
         pass



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



    def  _lowercase						(self   :   Any			):
         UpperCAmelCase_   ,			UpperCAmelCase_	   =       self.model_tester.prepare_config_and_inputs_for_common()

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

              UpperCAmelCase_	   =       ["pixel_values"]
              self.assertListEqual(arg_names[:1]       ,      __a			)



    def  _lowercase						(self   :   Optional[int]			):
         def check_hidden_states_output(__a   :   Dict       ,      __a   :   str       ,      __a   :   Union[str, Any]			):
              UpperCAmelCase_	   =       model_class(__a			)

              UpperCAmelCase_	   =       model(**self._prepare_for_class(__a       ,      __a			)			)

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

              UpperCAmelCase_	   =       self.model_tester.num_stages
              self.assertEqual(len(__a			)       ,      expected_num_stages + 1			)

         UpperCAmelCase_   ,			UpperCAmelCase_	   =       self.model_tester.prepare_config_and_inputs_for_common()

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

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

              check_hidden_states_output(__a       ,      __a       ,      __a			)






    def  _lowercase						(self   :   Dict			):
         UpperCAmelCase_   ,			UpperCAmelCase_	   =       self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              with self.subTest(model_class.__name__			):
                   UpperCAmelCase_	   =       self._prepare_for_class(__a       ,      __a			)
                   UpperCAmelCase_	   =       model_class(__a			)

                   @jax.jit
                   def model_jitted(__a   :   str       ,      **__a   :   Optional[Any]			):
                        return model(pixel_values=__a       ,      **__a			)

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

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

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





def      lowerCAmelCase_    ( )   ->				List[str]:


     '''simple docstring'''




     UpperCAmelCase_	   =       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"      )
     return image






@require_flax
class 	__A				(			unittest.TestCase     ):



    @cached_property
    def  _lowercase						(self   :   Union[str, Any]			):
         return AutoImageProcessor.from_pretrained("facebook/regnet-y-040"			) if is_vision_available() else None






    @slow
    def  _lowercase						(self   :   Dict			):
         UpperCAmelCase_	   =       FlaxRegNetForImageClassification.from_pretrained("facebook/regnet-y-040"			)

         UpperCAmelCase_	   =       self.default_image_processor
         UpperCAmelCase_	   =       prepare_img()
         UpperCAmelCase_	   =       image_processor(images=__a       ,      return_tensors="np"			)

         UpperCAmelCase_	   =       model(**__a			)

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

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

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





'''simple docstring'''





import unittest
from typing import Tuple

import torch

from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device
from diffusers.utils.testing_utils import require_torch




@require_torch
class 	__A				:



    @property
    def  _lowercase						(self   :   int			):
         return self.get_dummy_input()



    @property
    def  _lowercase						(self   :   Any			):
         if self.block_type == "down":
              return (4, 32, 16, 16)
         elif self.block_type == "mid":
              return (4, 32, 32, 32)
         elif self.block_type == "up":
              return (4, 32, 64, 64)

         raise ValueError(f"""'{self.block_type}' is not a supported block_type. Set it to 'up', 'mid', or 'down'."""			)



    def  _lowercase						(self   :   Tuple       ,      __a   :   List[str]=True       ,      __a   :   Any=False       ,      __a   :   List[Any]=False       ,      __a   :   Any=False       ,      ):
         UpperCAmelCase_	   =       4
         UpperCAmelCase_	   =       32
         UpperCAmelCase_	   =       (32, 32)

         UpperCAmelCase_	   =       torch.manual_seed(0			)
         UpperCAmelCase_	   =       torch.device(__a			)
         UpperCAmelCase_	   =       (batch_size, num_channels) + sizes
         UpperCAmelCase_	   =       randn_tensor(__a       ,      generator=__a       ,      device=__a			)
         UpperCAmelCase_	   =       {"hidden_states": hidden_states}

         if include_temb:
              UpperCAmelCase_	   =       128
              UpperCAmelCase_	   =       randn_tensor((batch_size, temb_channels)       ,      generator=__a       ,      device=__a			)

         if include_res_hidden_states_tuple:
              UpperCAmelCase_	   =       torch.manual_seed(1			)
              UpperCAmelCase_	   =       (randn_tensor(__a       ,      generator=__a       ,      device=__a			),)

         if include_encoder_hidden_states:
              UpperCAmelCase_	   =       floats_tensor((batch_size, 32, 32)			).to(__a			)

         if include_skip_sample:
              UpperCAmelCase_	   =       randn_tensor(((batch_size, 3) + sizes)       ,      generator=__a       ,      device=__a			)

         return dummy_input



    def  _lowercase						(self   :   Tuple			):
         UpperCAmelCase_	   =       {
             "in_channels": 32,
             "out_channels": 32,
             "temb_channels": 128,
         }
         if self.block_type == "up":
              UpperCAmelCase_	   =       32

         if self.block_type == "mid":
              init_dict.pop("out_channels"			)

         UpperCAmelCase_	   =       self.dummy_input
         return init_dict, inputs_dict



    def  _lowercase						(self   :   Tuple       ,      __a   :   Any			):
         UpperCAmelCase_   ,			UpperCAmelCase_	   =       self.prepare_init_args_and_inputs_for_common()
         UpperCAmelCase_	   =       self.block_class(**__a			)
         unet_block.to(__a			)
         unet_block.eval()

         with torch.no_grad():
              UpperCAmelCase_	   =       unet_block(**__a			)

         if isinstance(__a       ,      __a			):
              UpperCAmelCase_	   =       output[0]

         self.assertEqual(output.shape       ,      self.output_shape			)

         UpperCAmelCase_	   =       output[0, -1, -3:, -3:]
         UpperCAmelCase_	   =       torch.tensor(__a			).to(__a			)
         assert torch_all_close(output_slice.flatten()       ,      __a       ,      atol=5E-3			)






    @unittest.skipIf(torch_device == "mps"       ,      "Training is not supported in mps"			)
    def  _lowercase						(self   :   Dict			):
         UpperCAmelCase_   ,			UpperCAmelCase_	   =       self.prepare_init_args_and_inputs_for_common()
         UpperCAmelCase_	   =       self.block_class(**__a			)
         model.to(__a			)
         model.train()
         UpperCAmelCase_	   =       model(**__a			)

         if isinstance(__a       ,      __a			):
              UpperCAmelCase_	   =       output[0]

         UpperCAmelCase_	   =       torch.device(__a			)
         UpperCAmelCase_	   =       randn_tensor(output.shape       ,      device=__a			)
         UpperCAmelCase_	   =       torch.nn.functional.mse_loss(__a       ,      __a			)
         loss.backward()




