


"""simple docstring"""





import dataclasses
import json
import warnings
from dataclasses import dataclass, field
from time import time
from typing import List

from ..utils import logging


_UpperCamelCase							=      logging.get_logger(__name__)



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							Optional[int]=None    ,						SCREAMING_SNAKE_CASE       :							List[Any]=None   ):


							'''simple docstring'''







							return field(default_factory=lambda: default    ,						metadata=lowerCamelCase__   )
@dataclass
class 		SCREAMING_SNAKE_CASE_							:
				"""simple docstring"""
				__snake_case   :       List[str]	 =		list_field(
				    default=[]       ,  metadata={
				        """help""": (
				            """Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version"""
				            """ of all available models"""
				        )
				    }       ,  )

				__snake_case   :       List[int]	 =		list_field(
				    default=[8]       ,  metadata={"""help""": """List of batch sizes for which memory and time performance will be evaluated"""}   )

				__snake_case   :       List[int]	 =		list_field(
				    default=[8, 32, 1_28, 5_12]       ,  metadata={"""help""": """List of sequence lengths for which memory and time performance will be evaluated"""}       ,  )

				__snake_case   :       bool	 =		field(
				    default=snake_case__       ,  metadata={"""help""": """Whether to benchmark inference of model. Inference can be disabled via --no-inference."""}       ,  )
				__snake_case   :       bool	 =		field(
				    default=snake_case__       ,  metadata={"""help""": """Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."""}       ,  )
				__snake_case   :       bool	 =		field(
				    default=snake_case__       ,  metadata={"""help""": """Whether to run on available tpu devices. TPU can be disabled via --no-tpu."""}   )
				__snake_case   :       bool	 =		field(default=snake_case__       ,  metadata={"""help""": """Use FP16 to accelerate inference."""}   )
				__snake_case   :       bool	 =		field(default=snake_case__       ,  metadata={"""help""": """Benchmark training of model"""}   )
				__snake_case   :       bool	 =		field(default=snake_case__       ,  metadata={"""help""": """Verbose memory tracing"""}   )
				__snake_case   :       bool	 =		field(
				    default=snake_case__       ,  metadata={"""help""": """Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."""}       ,  )
				__snake_case   :       bool	 =		field(
				    default=snake_case__       ,  metadata={
				        """help""": """Whether to perform memory measurements. Memory measurements can be disabled via --no-memory"""
				    }       ,  )
				__snake_case   :       bool	 =		field(default=snake_case__       ,  metadata={"""help""": """Trace memory line by line"""}   )
				__snake_case   :       bool	 =		field(default=snake_case__       ,  metadata={"""help""": """Save result to a CSV file"""}   )
				__snake_case   :       bool	 =		field(default=snake_case__       ,  metadata={"""help""": """Save all print statements in a log file"""}   )
				__snake_case   :       bool	 =		field(default=snake_case__       ,  metadata={"""help""": """Whether to print environment information"""}   )
				__snake_case   :       bool	 =		field(
				    default=snake_case__       ,  metadata={
				        """help""": (
				            """Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use"""
				            """ multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled"""
				            """ for debugging / testing and on TPU."""
				        )
				    }       ,  )
				__snake_case   :       str	 =		field(
				    default=F'''inference_time_{round(time()   )}.csv'''       ,  metadata={"""help""": """CSV filename used if saving time results to csv."""}       ,  )
				__snake_case   :       str	 =		field(
				    default=F'''inference_memory_{round(time()   )}.csv'''       ,  metadata={"""help""": """CSV filename used if saving memory results to csv."""}       ,  )
				__snake_case   :       str	 =		field(
				    default=F'''train_time_{round(time()   )}.csv'''       ,  metadata={"""help""": """CSV filename used if saving time results to csv for training."""}       ,  )
				__snake_case   :       str	 =		field(
				    default=F'''train_memory_{round(time()   )}.csv'''       ,  metadata={"""help""": """CSV filename used if saving memory results to csv for training."""}       ,  )
				__snake_case   :       str	 =		field(
				    default=F'''env_info_{round(time()   )}.csv'''       ,  metadata={"""help""": """CSV filename used if saving environment information."""}       ,  )
				__snake_case   :       str	 =		field(
				    default=F'''log_{round(time()   )}.csv'''       ,  metadata={"""help""": """Log filename used if print statements are saved in log."""}       ,  )
				__snake_case   :       int	 =		field(default=3       ,  metadata={"""help""": """Times an experiment will be run."""}   )
				__snake_case   :       bool	 =		field(
				    default=snake_case__       ,  metadata={
				        """help""": (
				            """Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain"""
				            """ model weights."""
				        )
				    }       ,  )




				def 					__lowercase  (     self  :List[Any]			):
											warnings.warn(
											    f'The class {self.__class__} is deprecated. Hugging Face Benchmarking utils'
											    ''' are deprecated in general and it is advised to use external Benchmarking libraries '''
											    ''' to benchmark Transformer models.'''						,    UpperCamelCase_						,    )




				def 					__lowercase  (     self  :Union[str, Any]			):
											return json.dumps(dataclasses.asdict(self			)						,    indent=2			)




				@property
				def 					__lowercase  (     self  :Tuple			):
											if len(self.models			) <= 0:
																		raise ValueError(
																		    '''Please make sure you provide at least one model name / model identifier, *e.g.* `--models'''
																		    ''' bert-base-cased` or `args.models = [\'bert-base-cased\'].'''			)
											return self.models




				@property
				def 					__lowercase  (     self  :Optional[int]			):
											if not self.multi_process:
																		return False
											elif self.is_tpu:
																		logger.info('''Multiprocessing is currently not possible on TPU.'''			)
																		return False
											else:
																		return True











"""simple docstring"""





import gc
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

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


enable_full_determinism()
class 		SCREAMING_SNAKE_CASE_							(    snake_case__       ,  unittest.TestCase   ):
				"""simple docstring"""
				__snake_case   :       Union[str, Any]	 =		LDMTextToImagePipeline
				__snake_case   :       Optional[Any]	 =		TEXT_TO_IMAGE_PARAMS - {
				    """negative_prompt""",
				    """negative_prompt_embeds""",
				    """cross_attention_kwargs""",
				    """prompt_embeds""",
				}
				__snake_case   :       str	 =		PipelineTesterMixin.required_optional_params - {
				    """num_images_per_prompt""",
				    """callback""",
				    """callback_steps""",
				}
				__snake_case   :       Union[str, Any]	 =		TEXT_TO_IMAGE_BATCH_PARAMS
				__snake_case   :       Optional[Any]	 =		False




				def 					__lowercase  (     self  :List[str]			):
											torch.manual_seed(0			)
											__lowerCamelCase      :      str         =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						,    )
											__lowerCamelCase      :      str         =DDIMScheduler(
											    beta_start=0.00085						,    beta_end=0.012						,    beta_schedule='''scaled_linear'''						,    clip_sample=__lowercase						,    set_alpha_to_one=__lowercase						,    )
											torch.manual_seed(0			)
											__lowerCamelCase      :      Optional[int]         =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						,    )
											torch.manual_seed(0			)
											__lowerCamelCase      :      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						,    )
											__lowerCamelCase      :      Optional[int]         =CLIPTextModel(__lowercase			)
											__lowerCamelCase      :      Dict         =CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''			)

											__lowerCamelCase      :      Optional[int]         ={
											    '''unet''': unet,
											    '''scheduler''': scheduler,
											    '''vqvae''': vae,
											    '''bert''': text_encoder,
											    '''tokenizer''': tokenizer,
											}
											return components




				def 					__lowercase  (     self  :int						,    __lowercase  :Optional[int]						,    __lowercase  :Optional[Any]=0			):
											if str(__lowercase			).startswith('''mps'''			):
																		__lowerCamelCase      :      Any         =torch.manual_seed(__lowercase			)
											else:
																		__lowerCamelCase      :      str         =torch.Generator(device=__lowercase			).manual_seed(__lowercase			)
											__lowerCamelCase      :      Any         ={
											    '''prompt''': '''A painting of a squirrel eating a burger''',
											    '''generator''': generator,
											    '''num_inference_steps''': 2,
											    '''guidance_scale''': 6.0,
											    '''output_type''': '''numpy''',
											}
											return inputs




				def 					__lowercase  (     self  :List[str]			):
											__lowerCamelCase      :      List[str]         ='''cpu'''  # ensure determinism for the device-dependent torch.Generator

											__lowerCamelCase      :      str         =self.get_dummy_components()
											__lowerCamelCase      :      Optional[int]         =LDMTextToImagePipeline(**__lowercase			)
											pipe.to(__lowercase			)
											pipe.set_progress_bar_config(disable=__lowercase			)

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

											assert image.shape == (1, 16, 16, 3)
											__lowerCamelCase      :      Optional[Any]         =np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014]			)

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

@slow
@require_torch_gpu
class 		SCREAMING_SNAKE_CASE_							(    unittest.TestCase   ):
				"""simple docstring"""




				def 					__lowercase  (     self  :Any			):
											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()




				def 					__lowercase  (     self  :int						,    __lowercase  :Any						,    __lowercase  :Optional[int]=torch.floataa						,    __lowercase  :Dict=0			):
											__lowerCamelCase      :      List[str]         =torch.manual_seed(__lowercase			)
											__lowerCamelCase      :      List[str]         =np.random.RandomState(__lowercase			).standard_normal((1, 4, 32, 32)			)
											__lowerCamelCase      :      List[str]         =torch.from_numpy(__lowercase			).to(device=__lowercase						,    dtype=__lowercase			)
											__lowerCamelCase      :      Any         ={
											    '''prompt''': '''A painting of a squirrel eating a burger''',
											    '''latents''': latents,
											    '''generator''': generator,
											    '''num_inference_steps''': 3,
											    '''guidance_scale''': 6.0,
											    '''output_type''': '''numpy''',
											}
											return inputs




				def 					__lowercase  (     self  :Tuple			):
											__lowerCamelCase      :      int         =LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256'''			).to(__lowercase			)
											pipe.set_progress_bar_config(disable=__lowercase			)

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

											assert image.shape == (1, 256, 256, 3)
											__lowerCamelCase      :      Union[str, Any]         =np.array([0.51825, 0.52850, 0.52543, 0.54258, 0.52304, 0.52569, 0.54363, 0.55276, 0.56878]			)
											__lowerCamelCase      :      Dict         =np.abs(expected_slice - image_slice			).max()
											assert max_diff < 1e-3

@nightly
@require_torch_gpu
class 		SCREAMING_SNAKE_CASE_							(    unittest.TestCase   ):
				"""simple docstring"""




				def 					__lowercase  (     self  :Any			):
											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()




				def 					__lowercase  (     self  :Dict						,    __lowercase  :Optional[Any]						,    __lowercase  :int=torch.floataa						,    __lowercase  :Dict=0			):
											__lowerCamelCase      :      Any         =torch.manual_seed(__lowercase			)
											__lowerCamelCase      :      Dict         =np.random.RandomState(__lowercase			).standard_normal((1, 4, 32, 32)			)
											__lowerCamelCase      :      str         =torch.from_numpy(__lowercase			).to(device=__lowercase						,    dtype=__lowercase			)
											__lowerCamelCase      :      Dict         ={
											    '''prompt''': '''A painting of a squirrel eating a burger''',
											    '''latents''': latents,
											    '''generator''': generator,
											    '''num_inference_steps''': 50,
											    '''guidance_scale''': 6.0,
											    '''output_type''': '''numpy''',
											}
											return inputs




				def 					__lowercase  (     self  :Tuple			):
											__lowerCamelCase      :      Optional[int]         =LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256'''			).to(__lowercase			)
											pipe.set_progress_bar_config(disable=__lowercase			)

											__lowerCamelCase      :      List[Any]         =self.get_inputs(__lowercase			)
											__lowerCamelCase      :      Optional[int]         =pipe(**__lowercase			).images[0]

											__lowerCamelCase      :      Optional[int]         =load_numpy(
											    '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy'''			)
											__lowerCamelCase      :      Dict         =np.abs(expected_image - image			).max()
											assert max_diff < 1e-3




