


import unittest

import numpy as np
import torch

from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device

from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()


class 	A_ (	__UpperCamelCase ,				unittest.TestCase   ):




      '''simple docstring'''


      __snake_case 	=       DDIMPipeline
      __snake_case 	=       UNCONDITIONAL_IMAGE_GENERATION_PARAMS
      __snake_case 	=       PipelineTesterMixin.required_optional_params - {
          """num_images_per_prompt""",
          """latents""",
          """callback""",
          """callback_steps""",
      }
      __snake_case 	=       UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS
      __snake_case 	=       False




      def 					_snake_case     (    self:	Union[str, Any]    ):
       torch.manual_seed(0    )
       __lowerCamelCase		:							List[str]		 =						UNetaDModel(
           block_out_channels=(32, 64)						,				layers_per_block=2						,				sample_size=32						,				in_channels=3						,				out_channels=3						,				down_block_types=('DownBlock2D', 'AttnDownBlock2D')						,				up_block_types=('AttnUpBlock2D', 'UpBlock2D')						,				)
       __lowerCamelCase		:							str		 =						DDIMScheduler()
       __lowerCamelCase		:							Union[str, Any]		 =						{'unet': unet, 'scheduler': scheduler}
       return components




      def 					_snake_case     (    self:	Tuple						,				a:	Optional[Any]						,				a:	str=0    ):
       if str(a    ).startswith('mps'    ):
        __lowerCamelCase		:							Dict		 =						torch.manual_seed(a    )
       else:
        __lowerCamelCase		:							List[Any]		 =						torch.Generator(device=a    ).manual_seed(a    )
       __lowerCamelCase		:							Union[str, Any]		 =						{
           'batch_size': 1,
           'generator': generator,
           'num_inference_steps': 2,
           'output_type': 'numpy',
       }
       return inputs




      def 					_snake_case     (    self:	str    ):
       __lowerCamelCase		:							Dict		 =						'cpu'

       __lowerCamelCase		:							Optional[Any]		 =						self.get_dummy_components()
       __lowerCamelCase		:							str		 =						self.pipeline_class(**a    )
       pipe.to(a    )
       pipe.set_progress_bar_config(disable=a    )

       __lowerCamelCase		:							Tuple		 =						self.get_dummy_inputs(a    )
       __lowerCamelCase		:							Optional[int]		 =						pipe(**a    ).images
       __lowerCamelCase		:							Any		 =						image[0, -3:, -3:, -1]

       self.assertEqual(image.shape						,				(1, 32, 32, 3)    )
       __lowerCamelCase		:							str		 =						np.array(
           [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04]    )
       __lowerCamelCase		:							Optional[int]		 =						np.abs(image_slice.flatten() - expected_slice    ).max()
       self.assertLessEqual(a						,				1e-3    )




      def 					_snake_case     (    self:	List[Any]    ):
       super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3    )




      def 					_snake_case     (    self:	Any    ):
       super().test_save_load_local(expected_max_difference=3e-3    )




      def 					_snake_case     (    self:	Dict    ):
       super().test_save_load_optional_components(expected_max_difference=3e-3    )




      def 					_snake_case     (    self:	Union[str, Any]    ):
       super().test_inference_batch_single_identical(expected_max_diff=3e-3    )



@slow
@require_torch_gpu
class 	A_ (	unittest.TestCase   ):




      '''simple docstring'''


      def 					_snake_case     (    self:	List[Any]    ):
       __lowerCamelCase		:							int		 =						'google/ddpm-cifar10-32'

       __lowerCamelCase		:							Union[str, Any]		 =						UNetaDModel.from_pretrained(a    )
       __lowerCamelCase		:							Any		 =						DDIMScheduler()

       __lowerCamelCase		:							Optional[int]		 =						DDIMPipeline(unet=a						,				scheduler=a    )
       ddim.to(a    )
       ddim.set_progress_bar_config(disable=a    )

       __lowerCamelCase		:							Any		 =						torch.manual_seed(0    )
       __lowerCamelCase		:							str		 =						ddim(generator=a						,				eta=0.0						,				output_type='numpy'    ).images

       __lowerCamelCase		:							Any		 =						image[0, -3:, -3:, -1]

       assert image.shape == (1, 32, 32, 3)
       __lowerCamelCase		:							Tuple		 =						np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3]    )

       assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-2




      def 					_snake_case     (    self:	Optional[Any]    ):
       __lowerCamelCase		:							str		 =						'google/ddpm-ema-bedroom-256'

       __lowerCamelCase		:							Any		 =						UNetaDModel.from_pretrained(a    )
       __lowerCamelCase		:							Dict		 =						DDIMScheduler.from_pretrained(a    )

       __lowerCamelCase		:							Any		 =						DDIMPipeline(unet=a						,				scheduler=a    )
       ddpm.to(a    )
       ddpm.set_progress_bar_config(disable=a    )

       __lowerCamelCase		:							Union[str, Any]		 =						torch.manual_seed(0    )
       __lowerCamelCase		:							str		 =						ddpm(generator=a						,				output_type='numpy'    ).images

       __lowerCamelCase		:							Any		 =						image[0, -3:, -3:, -1]

       assert image.shape == (1, 256, 256, 3)
       __lowerCamelCase		:							int		 =						np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9]    )

       assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-2





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




      def 					_snake_case     (    self:	int    ):
       __lowerCamelCase		:							Optional[Any]		 =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

       return config, pixel_values




      def 					_snake_case     (    self:	List[str]    ):
       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 					_snake_case     (    self:	Tuple						,				a:	Optional[int]						,				a:	int    ):
       __lowerCamelCase		:							Optional[Any]		 =						FlaxRegNetModel(config=a    )
       __lowerCamelCase		:							List[str]		 =						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 					_snake_case     (    self:	Optional[int]						,				a:	List[Any]						,				a:	List[Any]    ):
       __lowerCamelCase		:							Tuple		 =						self.num_labels
       __lowerCamelCase		:							Union[str, Any]		 =						FlaxRegNetForImageClassification(config=a    )
       __lowerCamelCase		:							List[Any]		 =						model(a    )
       self.parent.assertEqual(result.logits.shape						,				(self.batch_size, self.num_labels)    )




      def 					_snake_case     (    self:	Optional[Any]    ):
       __lowerCamelCase		:							Union[str, Any]		 =						self.prepare_config_and_inputs()
       __lowerCamelCase ,					__lowerCamelCase		:							str		 =						config_and_inputs
       __lowerCamelCase		:							Tuple		 =						{'pixel_values': pixel_values}
       return config, inputs_dict



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




      '''simple docstring'''


      __snake_case 	=       (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

      __snake_case 	=       False
      __snake_case 	=       False
      __snake_case 	=       False




      def 					_snake_case     (    self:	Tuple    ):
       __lowerCamelCase		:							Dict		 =						FlaxRegNetModelTester(self    )
       __lowerCamelCase		:							List[str]		 =						ConfigTester(self						,				config_class=a						,				has_text_modality=a    )




      def 					_snake_case     (    self:	Union[str, Any]    ):
       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:	List[Any]    ):
       return




      def 					_snake_case     (    self:	Dict    ):
       __lowerCamelCase		:							Union[str, Any]		 =						self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*a    )




      def 					_snake_case     (    self:	Optional[int]    ):
       __lowerCamelCase		:							Union[str, Any]		 =						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 					_snake_case     (    self:	Tuple    ):
       pass




      @unittest.skip(reason='RegNet does not support input and output embeddings'    )
      def 					_snake_case     (    self:	str    ):
       pass




      def 					_snake_case     (    self:	List[Any]    ):
       __lowerCamelCase ,					__lowerCamelCase		:							Optional[Any]		 =						self.model_tester.prepare_config_and_inputs_for_common()

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

        __lowerCamelCase		:							Union[str, Any]		 =						['pixel_values']
        self.assertListEqual(arg_names[:1]						,				a    )




      def 					_snake_case     (    self:	List[str]    ):
       def check_hidden_states_output(a:	List[Any]						,				a:	List[Any]						,				a:	Union[str, Any]    ):
        __lowerCamelCase		:							str		 =						model_class(a    )

        __lowerCamelCase		:							Optional[Any]		 =						model(**self._prepare_for_class(a						,				a    )    )

        __lowerCamelCase		:							List[str]		 =						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

        __lowerCamelCase		:							List[str]		 =						self.model_tester.num_stages
        self.assertEqual(len(a    )						,				expected_num_stages + 1    )

       __lowerCamelCase ,					__lowerCamelCase		:							Dict		 =						self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        __lowerCamelCase		:							int		 =						True
        check_hidden_states_output(a						,				a						,				a    )

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

        check_hidden_states_output(a						,				a						,				a    )




      def 					_snake_case     (    self:	Dict    ):
       __lowerCamelCase ,					__lowerCamelCase		:							Optional[int]		 =						self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        with self.subTest(model_class.__name__    ):
         __lowerCamelCase		:							str		 =						self._prepare_for_class(a						,				a    )
         __lowerCamelCase		:							List[str]		 =						model_class(a    )

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

         with self.subTest('JIT Enabled'    ):
          __lowerCamelCase		:							List[str]		 =						model_jitted(**a    ).to_tuple()

         with self.subTest('JIT Disabled'    ):
          with jax.disable_jit():
           __lowerCamelCase		:							Optional[int]		 =						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 				UpperCamelCase__					(  ):
 __lowerCamelCase		:							List[str]		 =						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
 return image



@require_flax
class 	A_ (	unittest.TestCase   ):




      '''simple docstring'''


      @cached_property
      def 					_snake_case     (    self:	Tuple    ):
       return AutoImageProcessor.from_pretrained('facebook/regnet-y-040'    ) if is_vision_available() else None




      @slow
      def 					_snake_case     (    self:	Optional[Any]    ):
       __lowerCamelCase		:							Optional[Any]		 =						FlaxRegNetForImageClassification.from_pretrained('facebook/regnet-y-040'    )

       __lowerCamelCase		:							Tuple		 =						self.default_image_processor
       __lowerCamelCase		:							int		 =						prepare_img()
       __lowerCamelCase		:							Tuple		 =						image_processor(images=a						,				return_tensors='np'    )

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

       # verify the logits
       __lowerCamelCase		:							str		 =						(1, 1000)
       self.assertEqual(outputs.logits.shape						,				a    )

       __lowerCamelCase		:							int		 =						jnp.array([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6]    )

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

