





"""simple docstring"""



import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMParallelScheduler,
    DDPMParallelScheduler,
    StableDiffusionParadigmsPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    require_torch_gpu,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()






class 	__snake_case      (	SCREAMING_SNAKE_CASE__							,							SCREAMING_SNAKE_CASE__							,							unittest.TestCase  ):





	"""simple docstring"""


	_lowerCamelCase				 =  StableDiffusionParadigmsPipeline
	_lowerCamelCase				 =  TEXT_TO_IMAGE_PARAMS
	_lowerCamelCase				 =  TEXT_TO_IMAGE_BATCH_PARAMS
	_lowerCamelCase				 =  TEXT_TO_IMAGE_IMAGE_PARAMS
	_lowerCamelCase				 =  TEXT_TO_IMAGE_IMAGE_PARAMS

	def       UpperCamelCase__(					self						):



					'''simple docstring'''




					torch.manual_seed(0						)
					__A					:		Optional[int]						=  UNetaDConditionModel(
					    block_out_channels=(32, 64)      ,		layers_per_block=2      ,		sample_size=32      ,		in_channels=4      ,		out_channels=4      ,		down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')      ,		up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')      ,		cross_attention_dim=32      ,		attention_head_dim=(2, 4)      ,		use_linear_projection=__lowerCamelCase      ,		)
					__A					:		Tuple						=  DDIMParallelScheduler(
					    beta_start=0.0_0_0_8_5      ,		beta_end=0.0_1_2      ,		beta_schedule='''scaled_linear'''      ,		clip_sample=__lowerCamelCase      ,		set_alpha_to_one=__lowerCamelCase      ,		)
					torch.manual_seed(0						)
					__A					:		Union[str, Any]						=  AutoencoderKL(
					    block_out_channels=[32, 64]      ,		in_channels=3      ,		out_channels=3      ,		down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']      ,		up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']      ,		latent_channels=4      ,		sample_size=128      ,		)
					torch.manual_seed(0						)
					__A					:		Any						=  CLIPTextConfig(
					    bos_token_id=0      ,		eos_token_id=2      ,		hidden_size=32      ,		intermediate_size=37      ,		layer_norm_eps=1e-0_5      ,		num_attention_heads=4      ,		num_hidden_layers=5      ,		pad_token_id=1      ,		vocab_size=1000      ,		hidden_act='''gelu'''      ,		projection_dim=512      ,		)
					__A					:		Tuple						=  CLIPTextModel(__lowerCamelCase						)
					__A					:		str						=  CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''						)

					__A					:		List[Any]						=  {
					    '''unet''': unet,
					    '''scheduler''': scheduler,
					    '''vae''': vae,
					    '''text_encoder''': text_encoder,
					    '''tokenizer''': tokenizer,
					    '''safety_checker''': None,
					    '''feature_extractor''': None,
					}
					return components

	def       UpperCamelCase__(					self      ,		__lowerCamelCase      ,		__lowerCamelCase=0						):



					'''simple docstring'''




					if str(__lowerCamelCase						).startswith('''mps'''						):
									__A					:		List[str]						=  torch.manual_seed(__lowerCamelCase						)
					else:
									__A					:		Optional[int]						=  torch.Generator(device=__lowerCamelCase						).manual_seed(__lowerCamelCase						)
					__A					:		Any						=  {
					    '''prompt''': '''a photograph of an astronaut riding a horse''',
					    '''generator''': generator,
					    '''num_inference_steps''': 10,
					    '''guidance_scale''': 6.0,
					    '''output_type''': '''numpy''',
					    '''parallel''': 3,
					    '''debug''': True,
					}
					return inputs

	def       UpperCamelCase__(					self						):



					'''simple docstring'''




					__A					:		Union[str, Any]						=  '''cpu'''  # ensure determinism for the device-dependent torch.Generator
					__A					:		Tuple						=  self.get_dummy_components()
					__A					:		List[Any]						=  StableDiffusionParadigmsPipeline(**__lowerCamelCase						)
					__A					:		Union[str, Any]						=  sd_pipe.to(__lowerCamelCase						)
					sd_pipe.set_progress_bar_config(disable=__lowerCamelCase						)

					__A					:		Dict						=  self.get_dummy_inputs(__lowerCamelCase						)
					__A					:		Optional[Any]						=  sd_pipe(**__lowerCamelCase						).images
					__A					:		str						=  image[0, -3:, -3:, -1]
					assert image.shape == (1, 64, 64, 3)

					__A					:		Optional[int]						=  np.array([0.4_7_7_3, 0.5_4_1_7, 0.4_7_2_3, 0.4_9_2_5, 0.5_6_3_1, 0.4_7_5_2, 0.5_2_4_0, 0.4_9_3_5, 0.5_0_2_3]						)

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

	def       UpperCamelCase__(					self						):



					'''simple docstring'''




					__A					:		Optional[Any]						=  '''cpu'''  # ensure determinism for the device-dependent torch.Generator
					__A					:		Union[str, Any]						=  self.get_dummy_components()
					torch.manual_seed(0						)
					__A					:		Any						=  DDPMParallelScheduler()
					torch.manual_seed(0						)
					__A					:		Dict						=  StableDiffusionParadigmsPipeline(**__lowerCamelCase						)
					__A					:		Tuple						=  sd_pipe.to(__lowerCamelCase						)
					sd_pipe.set_progress_bar_config(disable=__lowerCamelCase						)

					__A					:		Union[str, Any]						=  self.get_dummy_inputs(__lowerCamelCase						)
					__A					:		List[str]						=  sd_pipe(**__lowerCamelCase						).images
					__A					:		Union[str, Any]						=  image[0, -3:, -3:, -1]
					assert image.shape == (1, 64, 64, 3)

					__A					:		Any						=  np.array([0.3_5_7_3, 0.4_4_2_0, 0.4_9_6_0, 0.4_7_9_9, 0.3_7_9_6, 0.3_8_7_9, 0.4_8_1_9, 0.4_3_6_5, 0.4_4_6_8]						)

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

	def       UpperCamelCase__(					self						):



					'''simple docstring'''




					super().test_inference_batch_consistent(batch_sizes=[1, 2]						)

	def       UpperCamelCase__(					self						):



					'''simple docstring'''




					super().test_inference_batch_single_identical(batch_size=2      ,		expected_max_diff=3e-3						)







	def       UpperCamelCase__(					self						):



					'''simple docstring'''




					__A					:		List[Any]						=  '''cpu'''  # ensure determinism for the device-dependent torch.Generator
					__A					:		Union[str, Any]						=  self.get_dummy_components()
					__A					:		str						=  StableDiffusionParadigmsPipeline(**__lowerCamelCase						)
					__A					:		Union[str, Any]						=  sd_pipe.to(__lowerCamelCase						)
					sd_pipe.set_progress_bar_config(disable=__lowerCamelCase						)

					__A					:		Tuple						=  self.get_dummy_inputs(__lowerCamelCase						)
					__A					:		List[str]						=  '''french fries'''
					__A					:		Any						=  sd_pipe(**__lowerCamelCase      ,		negative_prompt=__lowerCamelCase						)
					__A					:		Dict						=  output.images
					__A					:		Dict						=  image[0, -3:, -3:, -1]

					assert image.shape == (1, 64, 64, 3)

					__A					:		Optional[Any]						=  np.array([0.4_7_7_1, 0.5_4_2_0, 0.4_6_8_3, 0.4_9_1_8, 0.5_6_3_6, 0.4_7_2_5, 0.5_2_3_0, 0.4_9_2_3, 0.5_0_1_5]						)

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






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





	"""simple docstring"""


	def       UpperCamelCase__(					self						):



					'''simple docstring'''




					super().tearDown()
					gc.collect()
					torch.cuda.empty_cache()

	def       UpperCamelCase__(					self      ,		__lowerCamelCase=0						):



					'''simple docstring'''




					__A					:		Dict						=  torch.Generator(device=__lowerCamelCase						).manual_seed(__lowerCamelCase						)
					__A					:		int						=  {
					    '''prompt''': '''a photograph of an astronaut riding a horse''',
					    '''generator''': generator,
					    '''num_inference_steps''': 10,
					    '''guidance_scale''': 7.5,
					    '''output_type''': '''numpy''',
					    '''parallel''': 3,
					    '''debug''': True,
					}
					return inputs







	def       UpperCamelCase__(					self						):



					'''simple docstring'''




					__A					:		List[Any]						=  '''stabilityai/stable-diffusion-2-base'''
					__A					:		List[str]						=  DDIMParallelScheduler.from_pretrained(__lowerCamelCase      ,		subfolder='''scheduler'''						)
					__A					:		Dict						=  StableDiffusionParadigmsPipeline.from_pretrained(__lowerCamelCase      ,		scheduler=__lowerCamelCase      ,		safety_checker=__lowerCamelCase						)
					pipe.to(__lowerCamelCase						)
					pipe.set_progress_bar_config(disable=__lowerCamelCase						)
					pipe.enable_attention_slicing()

					__A					:		List[str]						=  self.get_inputs()
					__A					:		List[Any]						=  pipe(**__lowerCamelCase						).images
					__A					:		Tuple						=  image[0, -3:, -3:, -1].flatten()

					assert image.shape == (1, 512, 512, 3)

					__A					:		str						=  np.array([0.9_6_2_2, 0.9_6_0_2, 0.9_7_4_8, 0.9_5_9_1, 0.9_6_3_0, 0.9_6_9_1, 0.9_6_6_1, 0.9_6_3_1, 0.9_7_4_1]						)

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











"""simple docstring"""



from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


a_				=    {
    """configuration_layoutlm""": ["""LAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LayoutLMConfig""", """LayoutLMOnnxConfig"""],
    """tokenization_layoutlm""": ["""LayoutLMTokenizer"""],
}

try:
       if not is_tokenizers_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       a_				=    ["""LayoutLMTokenizerFast"""]

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       a_				=    [
           """LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST""",
           """LayoutLMForMaskedLM""",
           """LayoutLMForSequenceClassification""",
           """LayoutLMForTokenClassification""",
           """LayoutLMForQuestionAnswering""",
           """LayoutLMModel""",
           """LayoutLMPreTrainedModel""",
       ]

try:
       if not is_tf_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       a_				=    [
           """TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST""",
           """TFLayoutLMForMaskedLM""",
           """TFLayoutLMForSequenceClassification""",
           """TFLayoutLMForTokenClassification""",
           """TFLayoutLMForQuestionAnswering""",
           """TFLayoutLMMainLayer""",
           """TFLayoutLMModel""",
           """TFLayoutLMPreTrainedModel""",
       ]


if TYPE_CHECKING:
       from .configuration_layoutlm import LAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMConfig, LayoutLMOnnxConfig
       from .tokenization_layoutlm import LayoutLMTokenizer

       try:
              if not is_tokenizers_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .tokenization_layoutlm_fast import LayoutLMTokenizerFast

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_layoutlm import (
                  LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
                  LayoutLMForMaskedLM,
                  LayoutLMForQuestionAnswering,
                  LayoutLMForSequenceClassification,
                  LayoutLMForTokenClassification,
                  LayoutLMModel,
                  LayoutLMPreTrainedModel,
              )
       try:
              if not is_tf_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_tf_layoutlm import (
                  TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
                  TFLayoutLMForMaskedLM,
                  TFLayoutLMForQuestionAnswering,
                  TFLayoutLMForSequenceClassification,
                  TFLayoutLMForTokenClassification,
                  TFLayoutLMMainLayer,
                  TFLayoutLMModel,
                  TFLayoutLMPreTrainedModel,
              )

else:
       import sys

       a_				=    _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)




