





"""simple docstring"""





import inspect
import unittest
import warnings
from math import ceil, floor

from transformers import LevitConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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


if is_torch_available():
							import torch

							from transformers import (
							    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
							    MODEL_MAPPING,
							    LevitForImageClassification,
							    LevitForImageClassificationWithTeacher,
							    LevitModel,
							)
							from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image

							from transformers import LevitImageProcessor
class 		SCREAMING_SNAKE_CASE_							(    snake_case__   ):
				"""simple docstring"""




				def 					__lowercase  (     self  :Any			):
											__lowerCamelCase      :      Optional[Any]         =self.config_class(**self.inputs_dict			)
											self.parent.assertTrue(hasattr(__lowercase						,    '''hidden_sizes'''			)			)
											self.parent.assertTrue(hasattr(__lowercase						,    '''num_attention_heads'''			)			)

class 		SCREAMING_SNAKE_CASE_							:
				"""simple docstring"""




				def __init__(     self  :Optional[Any]						,    __lowercase  :Optional[int]						,    __lowercase  :int=13						,    __lowercase  :Optional[Any]=64						,    __lowercase  :List[Any]=3						,    __lowercase  :Any=3						,    __lowercase  :Tuple=2						,    __lowercase  :Any=1						,    __lowercase  :Optional[Any]=16						,    __lowercase  :Any=[128, 256, 384]						,    __lowercase  :Any=[4, 6, 8]						,    __lowercase  :Optional[Any]=[2, 3, 4]						,    __lowercase  :Dict=[16, 16, 16]						,    __lowercase  :int=0						,    __lowercase  :Tuple=[2, 2, 2]						,    __lowercase  :Optional[Any]=[2, 2, 2]						,    __lowercase  :Union[str, Any]=0.02						,    __lowercase  :List[Any]=True						,    __lowercase  :Optional[Any]=True						,    __lowercase  :List[str]=2						,    ):
											__lowerCamelCase      :      int         =parent
											__lowerCamelCase      :      Any         =batch_size
											__lowerCamelCase      :      str         =image_size
											__lowerCamelCase      :      Any         =num_channels
											__lowerCamelCase      :      str         =kernel_size
											__lowerCamelCase      :      Union[str, Any]         =stride
											__lowerCamelCase      :      Any         =padding
											__lowerCamelCase      :      List[Any]         =hidden_sizes
											__lowerCamelCase      :      Any         =num_attention_heads
											__lowerCamelCase      :      str         =depths
											__lowerCamelCase      :      int         =key_dim
											__lowerCamelCase      :      Optional[Any]         =drop_path_rate
											__lowerCamelCase      :      Any         =patch_size
											__lowerCamelCase      :      int         =attention_ratio
											__lowerCamelCase      :      List[str]         =mlp_ratio
											__lowerCamelCase      :      Any         =initializer_range
											__lowerCamelCase      :      Tuple         =[
											    ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2],
											    ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2],
											]
											__lowerCamelCase      :      Union[str, Any]         =is_training
											__lowerCamelCase      :      Any         =use_labels
											__lowerCamelCase      :      Dict         =num_labels
											__lowerCamelCase      :      str         =initializer_range




				def 					__lowercase  (     self  :str			):
											__lowerCamelCase      :      Tuple         =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

											__lowerCamelCase      :      int         =None
											if self.use_labels:
																		__lowerCamelCase      :      Union[str, Any]         =ids_tensor([self.batch_size]						,    self.num_labels			)

											__lowerCamelCase      :      str         =self.get_config()
											return config, pixel_values, labels




				def 					__lowercase  (     self  :Optional[int]			):
											return LevitConfig(
											    image_size=self.image_size						,    num_channels=self.num_channels						,    kernel_size=self.kernel_size						,    stride=self.stride						,    padding=self.padding						,    patch_size=self.patch_size						,    hidden_sizes=self.hidden_sizes						,    num_attention_heads=self.num_attention_heads						,    depths=self.depths						,    key_dim=self.key_dim						,    drop_path_rate=self.drop_path_rate						,    mlp_ratio=self.mlp_ratio						,    attention_ratio=self.attention_ratio						,    initializer_range=self.initializer_range						,    down_ops=self.down_ops						,    )




				def 					__lowercase  (     self  :Tuple						,    __lowercase  :str						,    __lowercase  :str						,    __lowercase  :Any			):
											__lowerCamelCase      :      List[str]         =LevitModel(config=__lowercase			)
											model.to(__lowercase			)
											model.eval()
											__lowerCamelCase      :      int         =model(__lowercase			)
											__lowerCamelCase      :      Optional[Any]         =(self.image_size, self.image_size)
											__lowerCamelCase    ,						__lowerCamelCase      :      int         =image_size[0], image_size[1]
											for _ in range(4			):
																		__lowerCamelCase      :      Optional[int]         =floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1			)
																		__lowerCamelCase      :      Union[str, Any]         =floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1			)
											self.parent.assertEqual(
											    result.last_hidden_state.shape						,    (self.batch_size, ceil(height / 4			) * ceil(width / 4			), self.hidden_sizes[-1])						,    )




				def 					__lowercase  (     self  :Dict						,    __lowercase  :Tuple						,    __lowercase  :List[str]						,    __lowercase  :int			):
											__lowerCamelCase      :      int         =self.num_labels
											__lowerCamelCase      :      int         =LevitForImageClassification(__lowercase			)
											model.to(__lowercase			)
											model.eval()
											__lowerCamelCase      :      str         =model(__lowercase						,    labels=__lowercase			)
											self.parent.assertEqual(result.logits.shape						,    (self.batch_size, self.num_labels)			)




				def 					__lowercase  (     self  :int			):
											__lowerCamelCase      :      Optional[Any]         =self.prepare_config_and_inputs()
											__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase      :      Optional[Any]         =config_and_inputs
											__lowerCamelCase      :      List[Any]         ={'''pixel_values''': pixel_values}
											return config, inputs_dict

@require_torch
class 		SCREAMING_SNAKE_CASE_							(    snake_case__       ,  snake_case__       ,  unittest.TestCase   ):
				"""simple docstring"""
				__snake_case   :       List[Any]	 =		(
				    (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher)
				    if is_torch_available()
				    else ()
				)
				__snake_case   :       Union[str, Any]	 =		(
				    {
				        """feature-extraction""": LevitModel,
				        """image-classification""": (LevitForImageClassification, LevitForImageClassificationWithTeacher),
				    }
				    if is_torch_available()
				    else {}
				)

				__snake_case   :       Any	 =		False
				__snake_case   :       str	 =		False
				__snake_case   :       Optional[int]	 =		False
				__snake_case   :       Dict	 =		False
				__snake_case   :       Dict	 =		False




				def 					__lowercase  (     self  :List[str]			):
											__lowerCamelCase      :      str         =LevitModelTester(self			)
											__lowerCamelCase      :      Dict         =ConfigTester(self						,    config_class=__lowercase						,    has_text_modality=__lowercase						,    hidden_size=37			)




				def 					__lowercase  (     self  :str			):
											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 					__lowercase  (     self  :Dict			):
											return




				@unittest.skip(reason='''Levit does not use inputs_embeds'''			)
				def 					__lowercase  (     self  :Dict			):
											pass




				@unittest.skip(reason='''Levit does not support input and output embeddings'''			)
				def 					__lowercase  (     self  :List[Any]			):
											pass




				@unittest.skip(reason='''Levit does not output attentions'''			)
				def 					__lowercase  (     self  :Optional[Any]			):
											pass




				def 					__lowercase  (     self  :int			):
											__lowerCamelCase    ,						__lowerCamelCase      :      Dict         =self.model_tester.prepare_config_and_inputs_for_common()

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

																		__lowerCamelCase      :      Dict         =['''pixel_values''']
																		self.assertListEqual(arg_names[:1]						,    __lowercase			)




				def 					__lowercase  (     self  :List[str]			):
											def check_hidden_states_output(__lowercase  :Dict						,    __lowercase  :List[str]						,    __lowercase  :Any			):
																		__lowerCamelCase      :      Optional[Any]         =model_class(__lowercase			)
																		model.to(__lowercase			)
																		model.eval()

																		with torch.no_grad():
																									__lowerCamelCase      :      List[str]         =model(**self._prepare_for_class(__lowercase						,    __lowercase			)			)

																		__lowerCamelCase      :      Optional[int]         =outputs.hidden_states

																		__lowerCamelCase      :      Union[str, Any]         =len(self.model_tester.depths			) + 1
																		self.assertEqual(len(__lowercase			)						,    __lowercase			)

																		__lowerCamelCase      :      Optional[int]         =(self.model_tester.image_size, self.model_tester.image_size)
																		__lowerCamelCase    ,						__lowerCamelCase      :      List[str]         =image_size[0], image_size[1]
																		for _ in range(4			):
																									__lowerCamelCase      :      Union[str, Any]         =floor(
																									    (
																									        (height + 2 * self.model_tester.padding - self.model_tester.kernel_size)
																									        / self.model_tester.stride
																									    )
																									    + 1			)
																									__lowerCamelCase      :      List[Any]         =floor(
																									    (
																									        (width + 2 * self.model_tester.padding - self.model_tester.kernel_size)
																									        / self.model_tester.stride
																									    )
																									    + 1			)
																		# verify the first hidden states (first block)
																		self.assertListEqual(
																		    list(hidden_states[0].shape[-2:]			)						,    [
																		        height * width,
																		        self.model_tester.hidden_sizes[0],
																		    ]						,    )

											__lowerCamelCase    ,						__lowerCamelCase      :      List[str]         =self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																		__lowerCamelCase      :      List[str]         =True
																		check_hidden_states_output(__lowercase						,    __lowercase						,    __lowercase			)

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

																		check_hidden_states_output(__lowercase						,    __lowercase						,    __lowercase			)




				@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''			)
				def 					__lowercase  (     self  :List[str]			):
											pass




				def 					__lowercase  (     self  :Union[str, Any]						,    __lowercase  :List[str]						,    __lowercase  :Optional[Any]						,    __lowercase  :List[Any]=False			):
											__lowerCamelCase      :      Tuple         =super()._prepare_for_class(__lowercase						,    __lowercase						,    return_labels=__lowercase			)

											if return_labels:
																		if model_class.__name__ == "LevitForImageClassificationWithTeacher":
																									del inputs_dict["labels"]

											return inputs_dict




				def 					__lowercase  (     self  :int			):
											__lowerCamelCase      :      str         =self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*__lowercase			)




				def 					__lowercase  (     self  :str			):
											__lowerCamelCase      :      int         =self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*__lowercase			)




				def 					__lowercase  (     self  :int			):
											if not self.model_tester.is_training:
																		return

											__lowerCamelCase    ,						__lowerCamelCase      :      Optional[Any]         =self.model_tester.prepare_config_and_inputs_for_common()
											__lowerCamelCase      :      int         =True

											for model_class in self.all_model_classes:
																		# LevitForImageClassificationWithTeacher supports inference-only
																		if (
																		    model_class in get_values(__lowercase			)
																		    or model_class.__name__ == "LevitForImageClassificationWithTeacher"
																		):
																									continue
																		__lowerCamelCase      :      str         =model_class(__lowercase			)
																		model.to(__lowercase			)
																		model.train()
																		__lowerCamelCase      :      Any         =self._prepare_for_class(__lowercase						,    __lowercase						,    return_labels=__lowercase			)
																		__lowerCamelCase      :      List[Any]         =model(**__lowercase			).loss
																		loss.backward()




				def 					__lowercase  (     self  :str			):
											__lowerCamelCase    ,						__lowerCamelCase      :      Tuple         =self.model_tester.prepare_config_and_inputs_for_common()
											if not self.model_tester.is_training:
																		return

											__lowerCamelCase      :      Dict         =False
											__lowerCamelCase      :      Optional[Any]         =True

											for model_class in self.all_model_classes:
																		if model_class in get_values(__lowercase			) or not model_class.supports_gradient_checkpointing:
																									continue
																		# LevitForImageClassificationWithTeacher supports inference-only
																		if model_class.__name__ == "LevitForImageClassificationWithTeacher":
																									continue
																		__lowerCamelCase      :      Any         =model_class(__lowercase			)
																		model.gradient_checkpointing_enable()
																		model.to(__lowercase			)
																		model.train()
																		__lowerCamelCase      :      Optional[int]         =self._prepare_for_class(__lowercase						,    __lowercase						,    return_labels=__lowercase			)
																		__lowerCamelCase      :      Union[str, Any]         =model(**__lowercase			).loss
																		loss.backward()




				def 					__lowercase  (     self  :str			):
											__lowerCamelCase    ,						__lowerCamelCase      :      Any         =self.model_tester.prepare_config_and_inputs_for_common()

											__lowerCamelCase      :      Union[str, Any]         =[
											    {'''title''': '''multi_label_classification''', '''num_labels''': 2, '''dtype''': torch.float},
											    {'''title''': '''single_label_classification''', '''num_labels''': 1, '''dtype''': torch.long},
											    {'''title''': '''regression''', '''num_labels''': 1, '''dtype''': torch.float},
											]

											for model_class in self.all_model_classes:
																		if (
																		    model_class
																		    not in [
																		        *get_values(__lowercase			),
																		    ]
																		    or model_class.__name__ == "LevitForImageClassificationWithTeacher"
																		):
																									continue

																		for problem_type in problem_types:
																									with self.subTest(msg=f'Testing {model_class} with {problem_type["title"]}'			):
																																__lowerCamelCase      :      Union[str, Any]         =problem_type['''title''']
																																__lowerCamelCase      :      List[str]         =problem_type['''num_labels''']

																																__lowerCamelCase      :      Optional[Any]         =model_class(__lowercase			)
																																model.to(__lowercase			)
																																model.train()

																																__lowerCamelCase      :      Optional[int]         =self._prepare_for_class(__lowercase						,    __lowercase						,    return_labels=__lowercase			)

																																if problem_type["num_labels"] > 1:
																																							__lowerCamelCase      :      str         =inputs['''labels'''].unsqueeze(1			).repeat(1						,    problem_type['''num_labels''']			)

																																__lowerCamelCase      :      int         =inputs['''labels'''].to(problem_type['''dtype''']			)

																																# This tests that we do not trigger the warning form PyTorch "Using a target size that is different
																																# to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure
																																# they have the same size." which is a symptom something in wrong for the regression problem.
																																# See https://github.com/huggingface/transformers/issues/11780
																																with warnings.catch_warnings(record=__lowercase			) as warning_list:
																																							__lowerCamelCase      :      str         =model(**__lowercase			).loss
																																for w in warning_list:
																																							if "Using a target size that is different to the input size" in str(w.message			):
																																														raise ValueError(
																																														    f'Something is going wrong in the regression problem: intercepted {w.message}'			)

																																loss.backward()




				@slow
				def 					__lowercase  (     self  :List[str]			):
											for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		__lowerCamelCase      :      List[str]         =LevitModel.from_pretrained(__lowercase			)
																		self.assertIsNotNone(__lowercase			)



def 				lowerCAmelCase_			(      ):


							'''simple docstring'''







							__lowerCamelCase      :      Dict         =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
							return image
@require_torch
@require_vision
class 		SCREAMING_SNAKE_CASE_							(    unittest.TestCase   ):
				"""simple docstring"""




				@cached_property
				def 					__lowercase  (     self  :str			):
											return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]			)




				@slow
				def 					__lowercase  (     self  :int			):
											__lowerCamelCase      :      Optional[int]         =LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]			).to(
											    __lowercase			)

											__lowerCamelCase      :      Any         =self.default_image_processor
											__lowerCamelCase      :      Optional[int]         =prepare_img()
											__lowerCamelCase      :      List[str]         =image_processor(images=__lowercase						,    return_tensors='''pt'''			).to(__lowercase			)

											# forward pass
											with torch.no_grad():
																		__lowerCamelCase      :      List[str]         =model(**__lowercase			)

											# verify the logits
											__lowerCamelCase      :      int         =torch.Size((1, 1000)			)
											self.assertEqual(outputs.logits.shape						,    __lowercase			)

											__lowerCamelCase      :      str         =torch.tensor([1.0448, -0.3745, -1.8317]			).to(__lowercase			)

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











"""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




