





import inspect
import unittest

from datasets import load_dataset
from packaging import version

from transformers import BeitConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch
					from torch import nn

					from transformers import (
					    MODEL_MAPPING,
					    BeitForImageClassification,
					    BeitForMaskedImageModeling,
					    BeitForSemanticSegmentation,
					    BeitModel,
					)
					from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					import PIL
					from PIL import Image

					from transformers import BeitImageProcessor


class   A      :
			'''simple docstring'''




			def __init__(      self       :   int							,     __lowerCAmelCase       :   List[Any]							,     __lowerCAmelCase       :   Optional[Any]=1_00							,     __lowerCAmelCase       :   str=13							,     __lowerCAmelCase       :   int=30							,     __lowerCAmelCase       :   Any=2							,     __lowerCAmelCase       :   List[str]=3							,     __lowerCAmelCase       :   List[str]=True							,     __lowerCAmelCase       :   int=True							,     __lowerCAmelCase       :   str=32							,     __lowerCAmelCase       :   List[Any]=4							,     __lowerCAmelCase       :   Dict=4							,     __lowerCAmelCase       :   List[str]=37							,     __lowerCAmelCase       :   int="gelu"							,     __lowerCAmelCase       :   Optional[Any]=0.1							,     __lowerCAmelCase       :   Optional[Any]=0.1							,     __lowerCAmelCase       :   int=10							,     __lowerCAmelCase       :   Union[str, Any]=0.0_2							,     __lowerCAmelCase       :   Tuple=3							,     __lowerCAmelCase       :   List[str]=None							,     __lowerCAmelCase       :   Union[str, Any]=[0, 1, 2, 3]							,     )     ->     Tuple:







					"""simple docstring"""






					A__  				=       parent
					A__  				=       1_00
					A__  				=       batch_size
					A__  				=       image_size
					A__  				=       patch_size
					A__  				=       num_channels
					A__  				=       is_training
					A__  				=       use_labels
					A__  				=       hidden_size
					A__  				=       num_hidden_layers
					A__  				=       num_attention_heads
					A__  				=       intermediate_size
					A__  				=       hidden_act
					A__  				=       hidden_dropout_prob
					A__  				=       attention_probs_dropout_prob
					A__  				=       type_sequence_label_size
					A__  				=       initializer_range
					A__  				=       scope
					A__  				=       out_indices
					A__  				=       num_labels

					# in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
					A__  				=       (image_size // patch_size) ** 2
					A__  				=       num_patches + 1






			def        a_	(      self       :   Optional[int]       )     ->     Optional[Any]:







					"""simple docstring"""






					A__  				=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

					A__  				=       None
					A__  				=       None
					if self.use_labels:
							A__  				=       ids_tensor([self.batch_size]							,     self.type_sequence_label_size       )
							A__  				=       ids_tensor([self.batch_size, self.image_size, self.image_size]							,     self.num_labels       )

					A__  				=       self.get_config()

					return config, pixel_values, labels, pixel_labels






			def        a_	(      self       :   Optional[Any]       )     ->     Union[str, Any]:







					"""simple docstring"""






					return BeitConfig(
					    vocab_size=self.vocab_size							,     image_size=self.image_size							,     patch_size=self.patch_size							,     num_channels=self.num_channels							,     hidden_size=self.hidden_size							,     num_hidden_layers=self.num_hidden_layers							,     num_attention_heads=self.num_attention_heads							,     intermediate_size=self.intermediate_size							,     hidden_act=self.hidden_act							,     hidden_dropout_prob=self.hidden_dropout_prob							,     attention_probs_dropout_prob=self.attention_probs_dropout_prob							,     is_decoder=__lowerCAmelCase							,     initializer_range=self.initializer_range							,     out_indices=self.out_indices							,     )






			def        a_	(      self       :   Any							,     __lowerCAmelCase       :   str							,     __lowerCAmelCase       :   List[Any]							,     __lowerCAmelCase       :   List[Any]							,     __lowerCAmelCase       :   Dict       )     ->     List[str]:







					"""simple docstring"""






					A__  				=       BeitModel(config=__lowerCAmelCase       )
					model.to(__lowerCAmelCase       )
					model.eval()
					A__  				=       model(__lowerCAmelCase       )
					self.parent.assertEqual(result.last_hidden_state.shape							,     (self.batch_size, self.seq_length, self.hidden_size)       )






			def        a_	(      self       :   Optional[int]							,     __lowerCAmelCase       :   Optional[Any]							,     __lowerCAmelCase       :   Optional[int]							,     __lowerCAmelCase       :   List[str]							,     __lowerCAmelCase       :   List[str]       )     ->     Dict:







					"""simple docstring"""






					A__  				=       BeitForMaskedImageModeling(config=__lowerCAmelCase       )
					model.to(__lowerCAmelCase       )
					model.eval()
					A__  				=       model(__lowerCAmelCase       )
					self.parent.assertEqual(result.logits.shape							,     (self.batch_size, self.seq_length - 1, self.vocab_size)       )






			def        a_	(      self       :   int							,     __lowerCAmelCase       :   str							,     __lowerCAmelCase       :   List[str]							,     __lowerCAmelCase       :   int							,     __lowerCAmelCase       :   Any       )     ->     str:







					"""simple docstring"""






					A__  				=       self.type_sequence_label_size
					A__  				=       BeitForImageClassification(__lowerCAmelCase       )
					model.to(__lowerCAmelCase       )
					model.eval()
					A__  				=       model(__lowerCAmelCase							,     labels=__lowerCAmelCase       )
					self.parent.assertEqual(result.logits.shape							,     (self.batch_size, self.type_sequence_label_size)       )

					# test greyscale images
					A__  				=       1
					A__  				=       BeitForImageClassification(__lowerCAmelCase       )
					model.to(__lowerCAmelCase       )
					model.eval()

					A__  				=       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
					A__  				=       model(__lowerCAmelCase							,     labels=__lowerCAmelCase       )
					self.parent.assertEqual(result.logits.shape							,     (self.batch_size, self.type_sequence_label_size)       )






			def        a_	(      self       :   Optional[int]							,     __lowerCAmelCase       :   List[str]							,     __lowerCAmelCase       :   Union[str, Any]							,     __lowerCAmelCase       :   List[Any]							,     __lowerCAmelCase       :   List[Any]       )     ->     Optional[Any]:







					"""simple docstring"""






					A__  				=       self.num_labels
					A__  				=       BeitForSemanticSegmentation(__lowerCAmelCase       )
					model.to(__lowerCAmelCase       )
					model.eval()
					A__  				=       model(__lowerCAmelCase       )
					self.parent.assertEqual(
					    result.logits.shape							,     (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)       )
					A__  				=       model(__lowerCAmelCase							,     labels=__lowerCAmelCase       )
					self.parent.assertEqual(
					    result.logits.shape							,     (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)       )







			def        a_	(      self       :   str       )     ->     Dict:







					"""simple docstring"""






					A__  				=       self.prepare_config_and_inputs()
					A__				,      A__				,      A__				,      A__  				=       config_and_inputs
					A__  				=       {"""pixel_values""": pixel_values}
					return config, inputs_dict


@require_torch
class   A      (SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE       ,					unittest.TestCase   ):
			'''simple docstring'''




			__lowerCamelCase     :	Any          =   (
			    (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
			    if is_torch_available()
			    else ()
			)
			__lowerCamelCase     :	Optional[int]          =   (
			    {
			        '''feature-extraction''': BeitModel,
			        '''image-classification''': BeitForImageClassification,
			        '''image-segmentation''': BeitForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

			__lowerCamelCase     :	int          =   False
			__lowerCamelCase     :	int          =   False
			__lowerCamelCase     :	Dict          =   False






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







					"""simple docstring"""






					A__  				=       BeitModelTester(self       )
					A__  				=       ConfigTester(self							,     config_class=__lowerCAmelCase							,     has_text_modality=__lowerCAmelCase							,     hidden_size=37       )






			def        a_	(      self       :   int       )     ->     str:







					"""simple docstring"""






					self.config_tester.run_common_tests()






			@unittest.skip(reason="""BEiT does not use inputs_embeds"""       )
			def        a_	(      self       :   Union[str, Any]       )     ->     Tuple:







					"""simple docstring"""






					pass






			@require_torch_multi_gpu
			@unittest.skip(reason="""BEiT has some layers using `add_module` which doesn't work well with `nn.DataParallel`"""       )
			def        a_	(      self       :   List[str]       )     ->     Tuple:







					"""simple docstring"""






					pass






			def        a_	(      self       :   Dict       )     ->     Dict:







					"""simple docstring"""






					A__				,      A__  				=       self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
							A__  				=       model_class(__lowerCAmelCase       )
							self.assertIsInstance(model.get_input_embeddings()							,     (nn.Module)       )
							A__  				=       model.get_output_embeddings()
							self.assertTrue(x is None or isinstance(__lowerCAmelCase							,     nn.Linear       )       )






			def        a_	(      self       :   Optional[int]       )     ->     Tuple:







					"""simple docstring"""






					A__				,      A__  				=       self.model_tester.prepare_config_and_inputs_for_common()

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

							A__  				=       ["""pixel_values"""]
							self.assertListEqual(arg_names[:1]							,     __lowerCAmelCase       )






			def        a_	(      self       :   Optional[Any]       )     ->     Optional[int]:







					"""simple docstring"""






					A__  				=       self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*__lowerCAmelCase       )






			def        a_	(      self       :   int       )     ->     Optional[Any]:







					"""simple docstring"""






					A__  				=       self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_masked_lm(*__lowerCAmelCase       )






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







					"""simple docstring"""






					A__  				=       self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase       )






			def        a_	(      self       :   List[str]       )     ->     Union[str, Any]:







					"""simple docstring"""






					A__  				=       self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_semantic_segmentation(*__lowerCAmelCase       )






			def        a_	(      self       :   List[Any]       )     ->     Any:







					"""simple docstring"""






					if not self.model_tester.is_training:
							return

					A__				,      A__  				=       self.model_tester.prepare_config_and_inputs_for_common()
					A__  				=       True

					for model_class in self.all_model_classes:
							# we don't test BeitForMaskedImageModeling
							if model_class in [*get_values(__lowerCAmelCase       ), BeitForMaskedImageModeling]:
									continue

							A__  				=       model_class(__lowerCAmelCase       )
							model.to(__lowerCAmelCase       )
							model.train()
							A__  				=       self._prepare_for_class(__lowerCAmelCase							,     __lowerCAmelCase							,     return_labels=__lowerCAmelCase       )
							A__  				=       model(**__lowerCAmelCase       ).loss
							loss.backward()






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







					"""simple docstring"""






					A__				,      A__  				=       self.model_tester.prepare_config_and_inputs_for_common()
					if not self.model_tester.is_training:
							return

					A__  				=       False
					A__  				=       True

					for model_class in self.all_model_classes:
							# we don't test BeitForMaskedImageModeling
							if (
							    model_class in [*get_values(__lowerCAmelCase       ), BeitForMaskedImageModeling]
							    or not model_class.supports_gradient_checkpointing
							):
									continue

							A__  				=       model_class(__lowerCAmelCase       )
							model.gradient_checkpointing_enable()
							model.to(__lowerCAmelCase       )
							model.train()
							A__  				=       self._prepare_for_class(__lowerCAmelCase							,     __lowerCAmelCase							,     return_labels=__lowerCAmelCase       )
							A__  				=       model(**__lowerCAmelCase       ).loss
							loss.backward()






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







					"""simple docstring"""






					A__				,      A__  				=       self.model_tester.prepare_config_and_inputs_for_common()

					A__  				=       _config_zero_init(__lowerCAmelCase       )
					for model_class in self.all_model_classes:
							A__  				=       model_class(config=__lowerCAmelCase       )
							for name, param in model.named_parameters():
									# we skip lambda parameters as these require special initial values
									# determined by config.layer_scale_init_value
									if "lambda" in name:
											continue
									if param.requires_grad:
											self.assertIn(
											    ((param.data.mean() * 1e9).round() / 1e9).item()							,     [0.0, 1.0]							,     msg=f'Parameter {name} of model {model_class} seems not properly initialized'							,     )







			@slow
			def        a_	(      self       :   Optional[Any]       )     ->     Tuple:







					"""simple docstring"""






					for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							A__  				=       BeitModel.from_pretrained(__lowerCAmelCase       )
							self.assertIsNotNone(__lowerCAmelCase       )







def        __lowerCamelCase (							)		->    int:






		"""simple docstring"""

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






@require_torch
@require_vision
class   A      (unittest.TestCase   ):
			'''simple docstring'''




			@cached_property
			def        a_	(      self       :   Union[str, Any]       )     ->     Tuple:







					"""simple docstring"""






					return BeitImageProcessor.from_pretrained("""microsoft/beit-base-patch16-224"""       ) if is_vision_available() else None






			@slow
			def        a_	(      self       :   List[Any]       )     ->     Dict:







					"""simple docstring"""






					A__  				=       BeitForMaskedImageModeling.from_pretrained("""microsoft/beit-base-patch16-224-pt22k"""       ).to(__lowerCAmelCase       )

					A__  				=       self.default_image_processor
					A__  				=       prepare_img()
					A__  				=       image_processor(images=__lowerCAmelCase							,     return_tensors="""pt"""       ).pixel_values.to(__lowerCAmelCase       )

					# prepare bool_masked_pos
					A__  				=       torch.ones((1, 1_96)							,     dtype=torch.bool       ).to(__lowerCAmelCase       )

					# forward pass
					with torch.no_grad():
							A__  				=       model(pixel_values=__lowerCAmelCase							,     bool_masked_pos=__lowerCAmelCase       )
					A__  				=       outputs.logits

					# verify the logits
					A__  				=       torch.Size((1, 1_96, 81_92)       )
					self.assertEqual(logits.shape							,     __lowerCAmelCase       )

					A__  				=       torch.tensor(
					    [[-3.2_4_3_7, 0.5_0_7_2, -1_3.9_1_7_4], [-3.2_4_5_6, 0.4_9_4_8, -1_3.9_4_0_1], [-3.2_0_3_3, 0.5_1_2_1, -1_3.8_5_5_0]]       ).to(__lowerCAmelCase       )

					self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3]							,     __lowerCAmelCase							,     atol=1e-2       )       )






			@slow
			def        a_	(      self       :   Any       )     ->     Tuple:







					"""simple docstring"""






					A__  				=       BeitForImageClassification.from_pretrained("""microsoft/beit-base-patch16-224"""       ).to(__lowerCAmelCase       )

					A__  				=       self.default_image_processor
					A__  				=       prepare_img()
					A__  				=       image_processor(images=__lowerCAmelCase							,     return_tensors="""pt"""       ).to(__lowerCAmelCase       )

					# forward pass
					with torch.no_grad():
							A__  				=       model(**__lowerCAmelCase       )
					A__  				=       outputs.logits

					# verify the logits
					A__  				=       torch.Size((1, 10_00)       )
					self.assertEqual(logits.shape							,     __lowerCAmelCase       )

					A__  				=       torch.tensor([-1.2_3_8_5, -1.0_9_8_7, -1.0_1_0_8]       ).to(__lowerCAmelCase       )

					self.assertTrue(torch.allclose(logits[0, :3]							,     __lowerCAmelCase							,     atol=1e-4       )       )

					A__  				=       2_81
					self.assertEqual(logits.argmax(-1       ).item()							,     __lowerCAmelCase       )






			@slow
			def        a_	(      self       :   Dict       )     ->     Tuple:







					"""simple docstring"""






					A__  				=       BeitForImageClassification.from_pretrained("""microsoft/beit-large-patch16-224-pt22k-ft22k"""       ).to(
					    __lowerCAmelCase       )

					A__  				=       self.default_image_processor
					A__  				=       prepare_img()
					A__  				=       image_processor(images=__lowerCAmelCase							,     return_tensors="""pt"""       ).to(__lowerCAmelCase       )

					# forward pass
					with torch.no_grad():
							A__  				=       model(**__lowerCAmelCase       )
					A__  				=       outputs.logits

					# verify the logits
					A__  				=       torch.Size((1, 2_18_41)       )
					self.assertEqual(logits.shape							,     __lowerCAmelCase       )

					A__  				=       torch.tensor([1.6_8_8_1, -0.2_7_8_7, 0.5_9_0_1]       ).to(__lowerCAmelCase       )

					self.assertTrue(torch.allclose(logits[0, :3]							,     __lowerCAmelCase							,     atol=1e-4       )       )

					A__  				=       23_96
					self.assertEqual(logits.argmax(-1       ).item()							,     __lowerCAmelCase       )






			@slow
			def        a_	(      self       :   Tuple       )     ->     List[str]:







					"""simple docstring"""






					A__  				=       BeitForSemanticSegmentation.from_pretrained("""microsoft/beit-base-finetuned-ade-640-640"""       )
					A__  				=       model.to(__lowerCAmelCase       )

					A__  				=       BeitImageProcessor(do_resize=__lowerCAmelCase							,     size=6_40							,     do_center_crop=__lowerCAmelCase       )

					A__  				=       load_dataset("""hf-internal-testing/fixtures_ade20k"""							,     split="""test"""       )
					A__  				=       Image.open(ds[0]["""file"""]       )
					A__  				=       image_processor(images=__lowerCAmelCase							,     return_tensors="""pt"""       ).to(__lowerCAmelCase       )

					# forward pass
					with torch.no_grad():
							A__  				=       model(**__lowerCAmelCase       )
					A__  				=       outputs.logits

					# verify the logits
					A__  				=       torch.Size((1, 1_50, 1_60, 1_60)       )
					self.assertEqual(logits.shape							,     __lowerCAmelCase       )

					A__  				=       version.parse(PIL.__version__       ) < version.parse("""9.0.0"""       )

					if is_pillow_less_than_a:
							A__  				=       torch.tensor(
							    [
							        [[-4.9_2_2_5, -2.3_9_5_4, -3.0_5_2_2], [-2.8_8_2_2, -1.0_0_4_6, -1.7_5_6_1], [-2.9_5_4_9, -1.3_2_2_8, -2.1_3_4_7]],
							        [[-5.8_1_6_8, -3.4_1_2_9, -4.0_7_7_8], [-3.8_6_5_1, -2.2_2_1_4, -3.0_2_7_7], [-3.8_3_5_6, -2.4_6_4_3, -3.3_5_3_5]],
							        [[-0.0_0_7_8, 3.9_9_5_2, 4.0_7_5_4], [2.9_8_5_6, 4.6_9_4_4, 5.0_0_3_5], [3.2_4_1_3, 4.7_8_1_3, 4.9_9_6_9]],
							    ]							,     device=__lowerCAmelCase							,     )
					else:
							A__  				=       torch.tensor(
							    [
							        [[-4.8_9_6_0, -2.3_6_8_8, -3.0_3_5_5], [-2.8_4_7_8, -0.9_8_3_6, -1.7_4_1_8], [-2.9_4_4_9, -1.3_3_3_2, -2.1_4_5_6]],
							        [[-5.8_0_8_1, -3.4_1_2_4, -4.1_0_0_6], [-3.8_5_6_1, -2.2_0_8_1, -3.0_3_2_3], [-3.8_3_6_5, -2.4_6_0_1, -3.3_6_6_9]],
							        [[-0.0_3_0_9, 3.9_8_6_8, 4.0_5_4_0], [2.9_6_4_0, 4.6_8_7_7, 4.9_9_7_6], [3.2_0_8_1, 4.7_6_9_0, 4.9_9_4_2]],
							    ]							,     device=__lowerCAmelCase							,     )

					self.assertTrue(torch.allclose(logits[0, :3, :3, :3]							,     __lowerCAmelCase							,     atol=1e-4       )       )







			@slow
			def        a_	(      self       :   Union[str, Any]       )     ->     Any:







					"""simple docstring"""






					A__  				=       BeitForSemanticSegmentation.from_pretrained("""microsoft/beit-base-finetuned-ade-640-640"""       )
					A__  				=       model.to(__lowerCAmelCase       )

					A__  				=       BeitImageProcessor(do_resize=__lowerCAmelCase							,     size=6_40							,     do_center_crop=__lowerCAmelCase       )

					A__  				=       load_dataset("""hf-internal-testing/fixtures_ade20k"""							,     split="""test"""       )
					A__  				=       Image.open(ds[0]["""file"""]       )
					A__  				=       image_processor(images=__lowerCAmelCase							,     return_tensors="""pt"""       ).to(__lowerCAmelCase       )

					# forward pass
					with torch.no_grad():
							A__  				=       model(**__lowerCAmelCase       )

					A__  				=       outputs.logits.detach().cpu()

					A__  				=       image_processor.post_process_semantic_segmentation(outputs=__lowerCAmelCase							,     target_sizes=[(5_00, 3_00)]       )
					A__  				=       torch.Size((5_00, 3_00)       )
					self.assertEqual(segmentation[0].shape							,     __lowerCAmelCase       )

					A__  				=       image_processor.post_process_semantic_segmentation(outputs=__lowerCAmelCase       )
					A__  				=       torch.Size((1_60, 1_60)       )
					self.assertEqual(segmentation[0].shape							,     __lowerCAmelCase       )










import inspect
from typing import Callable, List, Optional, Union

import torch
from transformers import (
    CLIPImageProcessor,
    CLIPTextModel,
    CLIPTokenizer,
    WhisperForConditionalGeneration,
    WhisperProcessor,
)

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.utils import logging


A   : Any			=				logging.get_logger(__name__)  # pylint: disable=invalid-name


class   A      (SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''




			def __init__(      self       :   Optional[Any]							,     __lowerCAmelCase       :   WhisperForConditionalGeneration							,     __lowerCAmelCase       :   WhisperProcessor							,     __lowerCAmelCase       :   AutoencoderKL							,     __lowerCAmelCase       :   CLIPTextModel							,     __lowerCAmelCase       :   CLIPTokenizer							,     __lowerCAmelCase       :   UNetaDConditionModel							,     __lowerCAmelCase       :   Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]							,     __lowerCAmelCase       :   StableDiffusionSafetyChecker							,     __lowerCAmelCase       :   CLIPImageProcessor							,     )     ->     List[str]:







					"""simple docstring"""






					super().__init__()

					if safety_checker is None:
							logger.warning(
							    f'You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure'
							    """ that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"""
							    """ results in services or applications open to the public. Both the diffusers team and Hugging Face"""
							    """ strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"""
							    """ it only for use-cases that involve analyzing network behavior or auditing its results. For more"""
							    """ information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."""       )

					self.register_modules(
					    speech_model=__lowerCAmelCase							,     speech_processor=__lowerCAmelCase							,     vae=__lowerCAmelCase							,     text_encoder=__lowerCAmelCase							,     tokenizer=__lowerCAmelCase							,     unet=__lowerCAmelCase							,     scheduler=__lowerCAmelCase							,     feature_extractor=__lowerCAmelCase							,     )






			def        a_	(      self       :   Tuple							,     __lowerCAmelCase       :   Optional[Union[str, int]] = "auto"       )     ->     Union[str, Any]:







					"""simple docstring"""






					if slice_size == "auto":
							A__  				=       self.unet.config.attention_head_dim // 2
					self.unet.set_attention_slice(__lowerCAmelCase       )






			def        a_	(      self       :   Any       )     ->     str:







					"""simple docstring"""






					self.enable_attention_slicing(__lowerCAmelCase       )







			@torch.no_grad()
			def __call__(      self       :   Optional[Any]							,     __lowerCAmelCase       :   Dict							,     __lowerCAmelCase       :   int=1_60_00							,     __lowerCAmelCase       :   int = 5_12							,     __lowerCAmelCase       :   int = 5_12							,     __lowerCAmelCase       :   int = 50							,     __lowerCAmelCase       :   float = 7.5							,     __lowerCAmelCase       :   Optional[Union[str, List[str]]] = None							,     __lowerCAmelCase       :   Optional[int] = 1							,     __lowerCAmelCase       :   float = 0.0							,     __lowerCAmelCase       :   Optional[torch.Generator] = None							,     __lowerCAmelCase       :   Optional[torch.FloatTensor] = None							,     __lowerCAmelCase       :   Optional[str] = "pil"							,     __lowerCAmelCase       :   bool = True							,     __lowerCAmelCase       :   Optional[Callable[[int, int, torch.FloatTensor], None]] = None							,     __lowerCAmelCase       :   int = 1							,     **__lowerCAmelCase       :   Optional[Any]							,     )     ->     Any:







					"""simple docstring"""






					A__  				=       self.speech_processor.feature_extractor(
					    __lowerCAmelCase							,     return_tensors="""pt"""							,     sampling_rate=__lowerCAmelCase       ).input_features.to(self.device       )
					A__  				=       self.speech_model.generate(__lowerCAmelCase							,     max_length=48_00_00       )

					A__  				=       self.speech_processor.tokenizer.batch_decode(__lowerCAmelCase							,     skip_special_tokens=__lowerCAmelCase							,     normalize=__lowerCAmelCase       )[
					    0
					]

					if isinstance(__lowerCAmelCase							,     __lowerCAmelCase       ):
							A__  				=       1
					elif isinstance(__lowerCAmelCase							,     __lowerCAmelCase       ):
							A__  				=       len(__lowerCAmelCase       )
					else:
							raise ValueError(f'`prompt` has to be of type `str` or `list` but is {type(__lowerCAmelCase       )}'       )

					if height % 8 != 0 or width % 8 != 0:
							raise ValueError(f'`height` and `width` have to be divisible by 8 but are {height} and {width}.'       )

					if (callback_steps is None) or (
					    callback_steps is not None and (not isinstance(__lowerCAmelCase							,     __lowerCAmelCase       ) or callback_steps <= 0)
					):
							raise ValueError(
							    f'`callback_steps` has to be a positive integer but is {callback_steps} of type'
							    f' {type(__lowerCAmelCase       )}.'       )

					# get prompt text embeddings
					A__  				=       self.tokenizer(
					    __lowerCAmelCase							,     padding="""max_length"""							,     max_length=self.tokenizer.model_max_length							,     return_tensors="""pt"""							,     )
					A__  				=       text_inputs.input_ids

					if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
							A__  				=       self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]       )
							logger.warning(
							    """The following part of your input was truncated because CLIP can only handle sequences up to"""
							    f' {self.tokenizer.model_max_length} tokens: {removed_text}'       )
							A__  				=       text_input_ids[:, : self.tokenizer.model_max_length]
					A__  				=       self.text_encoder(text_input_ids.to(self.device       )       )[0]

					# duplicate text embeddings for each generation per prompt, using mps friendly method
					A__				,      A__				,      A__  				=       text_embeddings.shape
					A__  				=       text_embeddings.repeat(1							,     __lowerCAmelCase							,     1       )
					A__  				=       text_embeddings.view(bs_embed * num_images_per_prompt							,     __lowerCAmelCase							,     -1       )

					# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
					# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
					# corresponds to doing no classifier free guidance.
					A__  				=       guidance_scale > 1.0
					# get unconditional embeddings for classifier free guidance
					if do_classifier_free_guidance:
							A__  				=       42
							if negative_prompt is None:
									A__  				=       [""""""] * batch_size
							elif type(__lowerCAmelCase       ) is not type(__lowerCAmelCase       ):
									raise TypeError(
									    f'`negative_prompt` should be the same type to `prompt`, but got {type(__lowerCAmelCase       )} !='
									    f' {type(__lowerCAmelCase       )}.'       )
							elif isinstance(__lowerCAmelCase							,     __lowerCAmelCase       ):
									A__  				=       [negative_prompt]
							elif batch_size != len(__lowerCAmelCase       ):
									raise ValueError(
									    f'`negative_prompt`: {negative_prompt} has batch size {len(__lowerCAmelCase       )}, but `prompt`:'
									    f' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches'
									    """ the batch size of `prompt`."""       )
							else:
									A__  				=       negative_prompt

							A__  				=       text_input_ids.shape[-1]
							A__  				=       self.tokenizer(
							    __lowerCAmelCase							,     padding="""max_length"""							,     max_length=__lowerCAmelCase							,     truncation=__lowerCAmelCase							,     return_tensors="""pt"""							,     )
							A__  				=       self.text_encoder(uncond_input.input_ids.to(self.device       )       )[0]

							# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
							A__  				=       uncond_embeddings.shape[1]
							A__  				=       uncond_embeddings.repeat(1							,     __lowerCAmelCase							,     1       )
							A__  				=       uncond_embeddings.view(batch_size * num_images_per_prompt							,     __lowerCAmelCase							,     -1       )

							# For classifier free guidance, we need to do two forward passes.
							# Here we concatenate the unconditional and text embeddings into a single batch
							# to avoid doing two forward passes
							A__  				=       torch.cat([uncond_embeddings, text_embeddings]       )

					# get the initial random noise unless the user supplied it

					# Unlike in other pipelines, latents need to be generated in the target device
					# for 1-to-1 results reproducibility with the CompVis implementation.
					# However this currently doesn't work in `mps`.
					A__  				=       (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
					A__  				=       text_embeddings.dtype
					if latents is None:
							if self.device.type == "mps":
									# randn does not exist on mps
									A__  				=       torch.randn(__lowerCAmelCase							,     generator=__lowerCAmelCase							,     device="""cpu"""							,     dtype=__lowerCAmelCase       ).to(
									    self.device       )
							else:
									A__  				=       torch.randn(__lowerCAmelCase							,     generator=__lowerCAmelCase							,     device=self.device							,     dtype=__lowerCAmelCase       )
					else:
							if latents.shape != latents_shape:
									raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {latents_shape}'       )
							A__  				=       latents.to(self.device       )

					# set timesteps
					self.scheduler.set_timesteps(__lowerCAmelCase       )

					# Some schedulers like PNDM have timesteps as arrays
					# It's more optimized to move all timesteps to correct device beforehand
					A__  				=       self.scheduler.timesteps.to(self.device       )

					# scale the initial noise by the standard deviation required by the scheduler
					A__  				=       latents * self.scheduler.init_noise_sigma

					# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
					# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
					# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
					# and should be between [0, 1]
					A__  				=       """eta""" in set(inspect.signature(self.scheduler.step       ).parameters.keys()       )
					A__  				=       {}
					if accepts_eta:
							A__  				=       eta

					for i, t in enumerate(self.progress_bar(__lowerCAmelCase       )       ):
							# expand the latents if we are doing classifier free guidance
							A__  				=       torch.cat([latents] * 2       ) if do_classifier_free_guidance else latents
							A__  				=       self.scheduler.scale_model_input(__lowerCAmelCase							,     __lowerCAmelCase       )

							# predict the noise residual
							A__  				=       self.unet(__lowerCAmelCase							,     __lowerCAmelCase							,     encoder_hidden_states=__lowerCAmelCase       ).sample

							# perform guidance
							if do_classifier_free_guidance:
									A__				,      A__  				=       noise_pred.chunk(2       )
									A__  				=       noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

							# compute the previous noisy sample x_t -> x_t-1
							A__  				=       self.scheduler.step(__lowerCAmelCase							,     __lowerCAmelCase							,     __lowerCAmelCase							,     **__lowerCAmelCase       ).prev_sample

							# call the callback, if provided
							if callback is not None and i % callback_steps == 0:
									callback(__lowerCAmelCase							,     __lowerCAmelCase							,     __lowerCAmelCase       )

					A__  				=       1 / 0.1_8_2_1_5 * latents
					A__  				=       self.vae.decode(__lowerCAmelCase       ).sample

					A__  				=       (image / 2 + 0.5).clamp(0							,     1       )

					# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
					A__  				=       image.cpu().permute(0							,     2							,     3							,     1       ).float().numpy()

					if output_type == "pil":
							A__  				=       self.numpy_to_pil(__lowerCAmelCase       )

					if not return_dict:
							return image

					return StableDiffusionPipelineOutput(images=__lowerCAmelCase							,     nsfw_content_detected=__lowerCAmelCase       )



