




"""simple docstring"""






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 lowerCAmelCase__      :






			'''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    , ):
							_lowerCamelCase	:     Optional[Any]       =       parent
							_lowerCamelCase	:     List[Any]       =       batch_size
							_lowerCamelCase	:     List[str]       =       image_size
							_lowerCamelCase	:     List[str]       =       num_channels
							_lowerCamelCase	:     Tuple       =       embeddings_size
							_lowerCamelCase	:     Tuple       =       hidden_sizes
							_lowerCamelCase	:     Optional[Any]       =       depths
							_lowerCamelCase	:     Dict       =       is_training
							_lowerCamelCase	:     Optional[Any]       =       use_labels
							_lowerCamelCase	:     List[Any]       =       hidden_act
							_lowerCamelCase	:     List[str]       =       num_labels
							_lowerCamelCase	:     Any       =       scope
							_lowerCamelCase	:     Any       =       len(lowercase    )
			def    A_       (    self    ):
							_lowerCamelCase	:     str       =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

							_lowerCamelCase	:     Dict       =       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    , lowercase    , lowercase    , lowercase    ):
							_lowerCamelCase	:     List[Any]       =       TFRegNetModel(config=lowercase    )
							_lowerCamelCase	:     Optional[Any]       =       model(lowercase    , training=lowercase    )
							# 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    , lowercase    , lowercase    , lowercase    ):
							_lowerCamelCase	:     int       =       self.num_labels
							_lowerCamelCase	:     Any       =       TFRegNetForImageClassification(lowercase    )
							_lowerCamelCase	:     Union[str, Any]       =       model(lowercase    , labels=lowercase    , training=lowercase    )
							self.parent.assertEqual(result.logits.shape    , (self.batch_size, self.num_labels)    )






			def    A_       (    self    ):
							_lowerCamelCase	:     Dict       =       self.prepare_config_and_inputs()
							_lowerCamelCase,					_lowerCamelCase,					_lowerCamelCase	:     List[Any]       =       config_and_inputs
							_lowerCamelCase	:     Any       =       {'pixel_values': pixel_values}
							return config, inputs_dict






@require_tf
class lowerCAmelCase__      (	lowercase,      lowercase,      unittest.TestCase		):






			'''simple docstring'''



			lowerCamelCase__ =     (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
			lowerCamelCase__ =     (
			    {"""feature-extraction""": TFRegNetModel, """image-classification""": TFRegNetForImageClassification}
			    if is_tf_available()
			    else {}
			)

			lowerCamelCase__ =     False
			lowerCamelCase__ =     False
			lowerCamelCase__ =     False
			lowerCamelCase__ =     False
			lowerCamelCase__ =     False
			def    A_       (    self    ):
							_lowerCamelCase	:     Tuple       =       TFRegNetModelTester(self    )
							_lowerCamelCase	:     List[str]       =       ConfigTester(self    , config_class=lowercase    , has_text_modality=lowercase    )
			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    ):
							_lowerCamelCase,					_lowerCamelCase	:     Dict       =       self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
											_lowerCamelCase	:     Tuple       =       model_class(lowercase    )
											_lowerCamelCase	:     Dict       =       inspect.signature(model.call    )
											# signature.parameters is an OrderedDict => so arg_names order is deterministic
											_lowerCamelCase	:     Dict       =       [*signature.parameters.keys()]

											_lowerCamelCase	:     Dict       =       ['pixel_values']
											self.assertListEqual(arg_names[:1]    , lowercase    )
			def    A_       (    self    ):
							_lowerCamelCase	:     Union[str, Any]       =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowercase    )
			def    A_       (    self    ):
							def check_hidden_states_output(lowercase    , lowercase    , lowercase    ):
											_lowerCamelCase	:     List[Any]       =       model_class(lowercase    )
											_lowerCamelCase	:     Any       =       model(**self._prepare_for_class(lowercase    , lowercase    )    , training=lowercase    )

											_lowerCamelCase	:     Optional[int]       =       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

											_lowerCamelCase	:     List[str]       =       self.model_tester.num_stages
											self.assertEqual(len(lowercase    )    , 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]    , )

							_lowerCamelCase,					_lowerCamelCase	:     Dict       =       self.model_tester.prepare_config_and_inputs_for_common()
							_lowerCamelCase	:     int       =       ['basic', 'bottleneck']
							for model_class in self.all_model_classes:
											for layer_type in layers_type:
															_lowerCamelCase	:     int       =       layer_type
															_lowerCamelCase	:     List[Any]       =       True
															check_hidden_states_output(lowercase    , lowercase    , lowercase    )

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

															check_hidden_states_output(lowercase    , lowercase    , lowercase    )
			def    A_       (    self    ):
							_lowerCamelCase,					_lowerCamelCase	:     Any       =       self.model_tester.prepare_config_and_inputs_for_common()

							def check_equivalence(lowercase    , lowercase    , lowercase    , lowercase={}    ):
											_lowerCamelCase	:     Optional[Any]       =       model(lowercase    , return_dict=lowercase    , **lowercase    )
											_lowerCamelCase	:     List[str]       =       model(lowercase    , return_dict=lowercase    , **lowercase    ).to_tuple()

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

															recursive_check(lowercase    , lowercase    )

							for model_class in self.all_model_classes:
											_lowerCamelCase	:     List[Any]       =       model_class(lowercase    )

											_lowerCamelCase	:     List[Any]       =       self._prepare_for_class(lowercase    , lowercase    )
											_lowerCamelCase	:     Dict       =       self._prepare_for_class(lowercase    , lowercase    )
											check_equivalence(lowercase    , lowercase    , lowercase    )

											_lowerCamelCase	:     Optional[int]       =       self._prepare_for_class(lowercase    , lowercase    , return_labels=lowercase    )
											_lowerCamelCase	:     List[Any]       =       self._prepare_for_class(lowercase    , lowercase    , return_labels=lowercase    )
											check_equivalence(lowercase    , lowercase    , lowercase    )

											_lowerCamelCase	:     List[str]       =       self._prepare_for_class(lowercase    , lowercase    )
											_lowerCamelCase	:     List[str]       =       self._prepare_for_class(lowercase    , lowercase    )
											check_equivalence(lowercase    , lowercase    , lowercase    , {'output_hidden_states': True}    )

											_lowerCamelCase	:     List[str]       =       self._prepare_for_class(lowercase    , lowercase    , return_labels=lowercase    )
											_lowerCamelCase	:     int       =       self._prepare_for_class(lowercase    , lowercase    , return_labels=lowercase    )
											check_equivalence(lowercase    , lowercase    , lowercase    , {'output_hidden_states': True}    )
			def    A_       (    self    ):
							_lowerCamelCase	:     str       =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*lowercase    )






			@slow
			def    A_       (    self    ):
							for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											_lowerCamelCase	:     Union[str, Any]       =       TFRegNetModel.from_pretrained(lowercase    )
											self.assertIsNotNone(lowercase    )







def 	_snake_case     (							):
				_lowerCamelCase	:     Union[str, Any]       =       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
				return image






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






			'''simple docstring'''



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

							_lowerCamelCase	:     int       =       self.default_image_processor
							_lowerCamelCase	:     List[str]       =       prepare_img()
							_lowerCamelCase	:     List[str]       =       image_processor(images=lowercase    , return_tensors='tf'    )

							# forward pass
							_lowerCamelCase	:     List[Any]       =       model(**lowercase    , training=lowercase    )

							# verify the logits
							_lowerCamelCase	:     str       =       tf.TensorShape((1, 1000)    )
							self.assertEqual(outputs.logits.shape    , lowercase    )

							_lowerCamelCase	:     List[str]       =       tf.constant([-0.41_80, -1.50_51, -3.48_36]    )

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





"""simple docstring"""






import gc
import unittest

import numpy as np
import torch

from diffusers import (
    AudioDiffusionPipeline,
    AutoencoderKL,
    DDIMScheduler,
    DDPMScheduler,
    DiffusionPipeline,
    Mel,
    UNetaDConditionModel,
    UNetaDModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()






class lowerCAmelCase__      (	unittest.TestCase		):






			'''simple docstring'''



			def    A_       (    self    ):
							# clean up the VRAM after each test
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()
			@property
			def    A_       (    self    ):
							torch.manual_seed(0    )
							_lowerCamelCase	:     Union[str, Any]       =       UNetaDModel(
							    sample_size=(32, 64)    , in_channels=1    , out_channels=1    , layers_per_block=2    , block_out_channels=(128, 128)    , down_block_types=('AttnDownBlock2D', 'DownBlock2D')    , up_block_types=('UpBlock2D', 'AttnUpBlock2D')    , )
							return model
			@property
			def    A_       (    self    ):
							torch.manual_seed(0    )
							_lowerCamelCase	:     Dict       =       UNetaDConditionModel(
							    sample_size=(64, 32)    , in_channels=1    , out_channels=1    , layers_per_block=2    , block_out_channels=(128, 128)    , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D')    , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D')    , cross_attention_dim=10    , )
							return model
			@property
			def    A_       (    self    ):
							torch.manual_seed(0    )
							_lowerCamelCase	:     List[str]       =       AutoencoderKL(
							    sample_size=(128, 64)    , in_channels=1    , out_channels=1    , latent_channels=1    , layers_per_block=2    , block_out_channels=(128, 128)    , down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D')    , up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D')    , )
							_lowerCamelCase	:     int       =       UNetaDModel(
							    sample_size=(64, 32)    , in_channels=1    , out_channels=1    , layers_per_block=2    , block_out_channels=(128, 128)    , down_block_types=('AttnDownBlock2D', 'DownBlock2D')    , up_block_types=('UpBlock2D', 'AttnUpBlock2D')    , )
							return vqvae, unet






			@slow
			def    A_       (    self    ):
							_lowerCamelCase	:     str       =       'cpu'  # ensure determinism for the device-dependent torch.Generator
							_lowerCamelCase	:     Optional[int]       =       Mel(
							    x_res=self.dummy_unet.config.sample_size[1]    , y_res=self.dummy_unet.config.sample_size[0]    , )

							_lowerCamelCase	:     List[str]       =       DDPMScheduler()
							_lowerCamelCase	:     List[Any]       =       AudioDiffusionPipeline(vqvae=lowercase    , unet=self.dummy_unet    , mel=lowercase    , scheduler=lowercase    )
							_lowerCamelCase	:     List[Any]       =       pipe.to(lowercase    )
							pipe.set_progress_bar_config(disable=lowercase    )

							_lowerCamelCase	:     Union[str, Any]       =       torch.Generator(device=lowercase    ).manual_seed(42    )
							_lowerCamelCase	:     Union[str, Any]       =       pipe(generator=lowercase    , steps=4    )
							_lowerCamelCase	:     Optional[Any]       =       output.audios[0]
							_lowerCamelCase	:     int       =       output.images[0]

							_lowerCamelCase	:     Dict       =       torch.Generator(device=lowercase    ).manual_seed(42    )
							_lowerCamelCase	:     Dict       =       pipe(generator=lowercase    , steps=4    , return_dict=lowercase    )
							_lowerCamelCase	:     List[str]       =       output[0][0]

							assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length)
							assert (
							    image.height == self.dummy_unet.config.sample_size[0]
							    and image.width == self.dummy_unet.config.sample_size[1]
							)
							_lowerCamelCase	:     Optional[Any]       =       np.frombuffer(image.tobytes()    , dtype='uint8'    )[:10]
							_lowerCamelCase	:     Dict       =       np.frombuffer(image_from_tuple.tobytes()    , dtype='uint8'    )[:10]
							_lowerCamelCase	:     List[str]       =       np.array([69, 255, 255, 255, 0, 0, 77, 181, 12, 127]    )

							assert np.abs(image_slice.flatten() - expected_slice    ).max() == 0
							assert np.abs(image_from_tuple_slice.flatten() - expected_slice    ).max() == 0

							_lowerCamelCase	:     List[Any]       =       Mel(
							    x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1]    , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0]    , )

							_lowerCamelCase	:     Dict       =       DDIMScheduler()
							_lowerCamelCase	:     Tuple       =       self.dummy_vqvae_and_unet
							_lowerCamelCase	:     List[str]       =       AudioDiffusionPipeline(
							    vqvae=self.dummy_vqvae_and_unet[0]    , unet=dummy_vqvae_and_unet[1]    , mel=lowercase    , scheduler=lowercase    )
							_lowerCamelCase	:     Tuple       =       pipe.to(lowercase    )
							pipe.set_progress_bar_config(disable=lowercase    )

							np.random.seed(0    )
							_lowerCamelCase	:     Any       =       np.random.uniform(-1    , 1    , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,)    )
							_lowerCamelCase	:     Optional[int]       =       torch.Generator(device=lowercase    ).manual_seed(42    )
							_lowerCamelCase	:     Dict       =       pipe(raw_audio=lowercase    , generator=lowercase    , start_step=5    , steps=10    )
							_lowerCamelCase	:     str       =       output.images[0]

							assert (
							    image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0]
							    and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1]
							)
							_lowerCamelCase	:     Dict       =       np.frombuffer(image.tobytes()    , dtype='uint8'    )[:10]
							_lowerCamelCase	:     Union[str, Any]       =       np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121]    )

							assert np.abs(image_slice.flatten() - expected_slice    ).max() == 0

							_lowerCamelCase	:     Dict       =       self.dummy_unet_condition
							_lowerCamelCase	:     Optional[int]       =       AudioDiffusionPipeline(
							    vqvae=self.dummy_vqvae_and_unet[0]    , unet=lowercase    , mel=lowercase    , scheduler=lowercase    )
							_lowerCamelCase	:     Dict       =       pipe.to(lowercase    )
							pipe.set_progress_bar_config(disable=lowercase    )

							np.random.seed(0    )
							_lowerCamelCase	:     Optional[int]       =       torch.rand((1, 1, 10)    )
							_lowerCamelCase	:     Optional[Any]       =       pipe(generator=lowercase    , encoding=lowercase    )
							_lowerCamelCase	:     Dict       =       output.images[0]
							_lowerCamelCase	:     Tuple       =       np.frombuffer(image.tobytes()    , dtype='uint8'    )[:10]
							_lowerCamelCase	:     List[str]       =       np.array([107, 103, 120, 127, 142, 122, 113, 122, 97, 111]    )

							assert np.abs(image_slice.flatten() - expected_slice    ).max() == 0






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






			'''simple docstring'''



			def    A_       (    self    ):
							# clean up the VRAM after each test
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()






			def    A_       (    self    ):
							_lowerCamelCase	:     Optional[Any]       =       torch_device

							_lowerCamelCase	:     Dict       =       DiffusionPipeline.from_pretrained('teticio/audio-diffusion-ddim-256'    )
							_lowerCamelCase	:     List[str]       =       pipe.to(lowercase    )
							pipe.set_progress_bar_config(disable=lowercase    )

							_lowerCamelCase	:     int       =       torch.Generator(device=lowercase    ).manual_seed(42    )
							_lowerCamelCase	:     Tuple       =       pipe(generator=lowercase    )
							_lowerCamelCase	:     Dict       =       output.audios[0]
							_lowerCamelCase	:     Dict       =       output.images[0]

							assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length)
							assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1]
							_lowerCamelCase	:     Optional[int]       =       np.frombuffer(image.tobytes()    , dtype='uint8'    )[:10]
							_lowerCamelCase	:     int       =       np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26]    )

							assert np.abs(image_slice.flatten() - expected_slice    ).max() == 0