





"""simple docstring"""





import json
import os
import re
import shutil
import tempfile
import unittest
from typing import Tuple

from transformers import AddedToken, BatchEncoding, ByTaTokenizer
from transformers.utils import cached_property, is_tf_available, is_torch_available

from ...test_tokenization_common import TokenizerTesterMixin


if is_torch_available():
							_UpperCamelCase							=      'pt'
elif is_tf_available():
							_UpperCamelCase							=      'tf'
else:
							_UpperCamelCase							=      'jax'
class 		SCREAMING_SNAKE_CASE_							(    snake_case__       ,  unittest.TestCase   ):
				"""simple docstring"""
				__snake_case   :       Optional[int]	 =		ByTaTokenizer
				__snake_case   :       Union[str, Any]	 =		False




				def 					__lowercase  (     self  :List[str]			):
											super().setUp()
											__lowerCamelCase      :      str         =ByTaTokenizer()
											tokenizer.save_pretrained(self.tmpdirname			)




				@cached_property
				def 					__lowercase  (     self  :Optional[Any]			):
											return ByTaTokenizer.from_pretrained('''google/byt5-small'''			)




				def 					__lowercase  (     self  :Optional[int]						,    **__lowercase  :Union[str, Any]			):
											return self.tokenizer_class.from_pretrained(self.tmpdirname						,    **__lowercase			)




				def 					__lowercase  (     self  :Any						,    __lowercase  :int						,    __lowercase  :List[Any]=False						,    __lowercase  :List[str]=20						,    __lowercase  :Any=5			):
											# XXX The default common tokenizer tests assume that every ID is decodable on its own.
											# This assumption is invalid for ByT5 because single bytes might not be
											# valid utf-8 (byte 128 for instance).
											# Here we're overriding the smallest possible method to provide
											# a clean sequence without making the same assumption.

											__lowerCamelCase      :      List[Any]         =[]
											for i in range(len(__lowercase			)			):
																		try:
																									__lowerCamelCase      :      Any         =tokenizer.decode([i]						,    clean_up_tokenization_spaces=__lowercase			)
																		except UnicodeDecodeError:
																									pass
																		toks.append((i, tok)			)

											__lowerCamelCase      :      Optional[Any]         =list(filter(lambda __lowercase			: re.match(r'''^[ a-zA-Z]+$'''						,    t[1]			)						,    __lowercase			)			)
											__lowerCamelCase      :      str         =list(filter(lambda __lowercase			: [t[0]] == tokenizer.encode(t[1]						,    add_special_tokens=__lowercase			)						,    __lowercase			)			)
											if max_length is not None and len(__lowercase			) > max_length:
																		__lowerCamelCase      :      Union[str, Any]         =toks[:max_length]
											if min_length is not None and len(__lowercase			) < min_length and len(__lowercase			) > 0:
																		while len(__lowercase			) < min_length:
																									__lowerCamelCase      :      Optional[Any]         =toks + toks
        # toks_str = [t[1] for t in toks]
											__lowerCamelCase      :      Tuple         =[t[0] for t in toks]

											# Ensure consistency
											__lowerCamelCase      :      List[Any]         =tokenizer.decode(__lowercase						,    clean_up_tokenization_spaces=__lowercase			)
											if " " not in output_txt and len(__lowercase			) > 1:
																		__lowerCamelCase      :      Optional[int]         =(
																		    tokenizer.decode([toks_ids[0]]						,    clean_up_tokenization_spaces=__lowercase			)
																		    + ''' '''
																		    + tokenizer.decode(toks_ids[1:]						,    clean_up_tokenization_spaces=__lowercase			)
																		)
											if with_prefix_space:
																		__lowerCamelCase      :      Any         =''' ''' + output_txt
											__lowerCamelCase      :      Any         =tokenizer.encode(__lowercase						,    add_special_tokens=__lowercase			)
											return output_txt, output_ids




				def 					__lowercase  (     self  :str			):
											__lowerCamelCase      :      Optional[Any]         =self.ta_base_tokenizer
											__lowerCamelCase      :      Optional[Any]         =tokenizer(['''hi</s>''', '''I went to the gym</s>''', '''</s>''']			)
											__lowerCamelCase      :      Tuple         =tokenizer(['''hi''', '''I went to the gym''', '''''']			)
											self.assertListEqual(batch_with_eos_added['''input_ids''']						,    batch_without_eos_added['''input_ids''']			)




				def 					__lowercase  (     self  :List[str]			):
											__lowerCamelCase      :      Optional[int]         =self.ta_base_tokenizer
											__lowerCamelCase      :      List[str]         ='''Unicode €.'''
											__lowerCamelCase      :      str         =tokenizer(__lowercase			)
											__lowerCamelCase      :      Union[str, Any]         =[88, 113, 108, 102, 114, 103, 104, 35, 229, 133, 175, 49, 1]
											self.assertEqual(encoded['''input_ids''']						,    __lowercase			)

											# decoding
											__lowerCamelCase      :      Dict         =tokenizer.decode(__lowercase			)
											self.assertEqual(__lowercase						,    '''Unicode €.</s>'''			)

											__lowerCamelCase      :      Union[str, Any]         =tokenizer('''e è é ê ë'''			)
											__lowerCamelCase      :      Optional[Any]         =[104, 35, 198, 171, 35, 198, 172, 35, 198, 173, 35, 198, 174, 1]
											self.assertEqual(encoded['''input_ids''']						,    __lowercase			)
											# decoding
											__lowerCamelCase      :      Any         =tokenizer.decode(__lowercase			)
											self.assertEqual(__lowercase						,    '''e è é ê ë</s>'''			)

											# encode/decode, but with `encode` instead of `__call__`
											self.assertEqual(tokenizer.decode(tokenizer.encode('''e è é ê ë'''			)			)						,    '''e è é ê ë</s>'''			)




				def 					__lowercase  (     self  :Tuple			):
											__lowerCamelCase      :      Any         =self.ta_base_tokenizer
											__lowerCamelCase      :      Optional[Any]         =['''A long paragraph for summarization.''', '''Another paragraph for summarization.''']
											# fmt: off
											__lowerCamelCase      :      str         =[68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 1, 0]
											# fmt: on
											__lowerCamelCase      :      Tuple         =tokenizer(__lowercase						,    padding=__lowercase						,    return_tensors=__lowercase			)
											self.assertIsInstance(__lowercase						,    __lowercase			)

											if FRAMEWORK != "jax":
																		__lowerCamelCase      :      Optional[Any]         =list(batch.input_ids.numpy()[0]			)
											else:
																		__lowerCamelCase      :      Tuple         =list(batch.input_ids.tolist()[0]			)

											self.assertListEqual(__lowercase						,    __lowercase			)

											self.assertEqual((2, 37)						,    batch.input_ids.shape			)
											self.assertEqual((2, 37)						,    batch.attention_mask.shape			)




				def 					__lowercase  (     self  :Dict			):
											__lowerCamelCase      :      int         =self.ta_base_tokenizer
											__lowerCamelCase      :      Union[str, Any]         =['''A long paragraph for summarization.''', '''Another paragraph for summarization.''']
											__lowerCamelCase      :      Optional[Any]         =tokenizer(__lowercase						,    padding=__lowercase						,    return_tensors=__lowercase			)
											# check if input_ids are returned and no decoder_input_ids
											self.assertIn('''input_ids'''						,    __lowercase			)
											self.assertIn('''attention_mask'''						,    __lowercase			)
											self.assertNotIn('''decoder_input_ids'''						,    __lowercase			)
											self.assertNotIn('''decoder_attention_mask'''						,    __lowercase			)




				def 					__lowercase  (     self  :str			):
											__lowerCamelCase      :      Optional[Any]         =self.ta_base_tokenizer
											__lowerCamelCase      :      int         =[
											    '''Summary of the text.''',
											    '''Another summary.''',
											]
											__lowerCamelCase      :      int         =tokenizer(
											    text_target=__lowercase						,    max_length=32						,    padding='''max_length'''						,    truncation=__lowercase						,    return_tensors=__lowercase			)
											self.assertEqual(32						,    targets['''input_ids'''].shape[1]			)




				def 					__lowercase  (     self  :str			):
											__lowerCamelCase      :      int         =self.ta_base_tokenizer
											__lowerCamelCase      :      Tuple         =['''A long paragraph for summarization. </s>''']
											__lowerCamelCase      :      Union[str, Any]         =['''Summary of the text. </s>''']
											# fmt: off
											__lowerCamelCase      :      List[Any]         =[68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 35, 1]
											__lowerCamelCase      :      Dict         =[86, 120, 112, 112, 100, 117, 124, 35, 114, 105, 35, 119, 107, 104, 35, 119, 104, 123, 119, 49, 35, 1]
											# fmt: on

											__lowerCamelCase      :      Optional[int]         =tokenizer(__lowercase						,    text_target=__lowercase			)

											self.assertEqual(__lowercase						,    batch['''input_ids'''][0]			)
											self.assertEqual(__lowercase						,    batch['''labels'''][0]			)




				def 					__lowercase  (     self  :Optional[int]			):
											# safety check on max_len default value so we are sure the test works
											__lowerCamelCase      :      List[Any]         =self.get_tokenizers()
											for tokenizer in tokenizers:
																		with self.subTest(f'{tokenizer.__class__.__name__}'			):
																									self.assertNotEqual(tokenizer.model_max_length						,    42			)

        # Now let's start the test
											__lowerCamelCase      :      Tuple         =self.get_tokenizers()
											for tokenizer in tokenizers:
																		with self.subTest(f'{tokenizer.__class__.__name__}'			):
																									# Isolate this from the other tests because we save additional tokens/etc
																									__lowerCamelCase      :      Any         =tempfile.mkdtemp()

																									__lowerCamelCase      :      Dict         =''' He is very happy, UNwant\u00E9d,running'''
																									__lowerCamelCase      :      List[Any]         =tokenizer.encode(__lowercase						,    add_special_tokens=__lowercase			)
																									tokenizer.save_pretrained(__lowercase			)

																									__lowerCamelCase      :      Optional[int]         =tokenizer.__class__.from_pretrained(__lowercase			)
																									__lowerCamelCase      :      Union[str, Any]         =after_tokenizer.encode(__lowercase						,    add_special_tokens=__lowercase			)
																									self.assertListEqual(__lowercase						,    __lowercase			)

																									shutil.rmtree(__lowercase			)

											__lowerCamelCase      :      Union[str, Any]         =self.get_tokenizers(model_max_length=42			)
											for tokenizer in tokenizers:
																		with self.subTest(f'{tokenizer.__class__.__name__}'			):
																									# Isolate this from the other tests because we save additional tokens/etc
																									__lowerCamelCase      :      int         =tempfile.mkdtemp()

																									__lowerCamelCase      :      int         =''' He is very happy, UNwant\u00E9d,running'''
																									tokenizer.add_tokens(['''bim''', '''bambam''']			)
																									__lowerCamelCase      :      Dict         =tokenizer.additional_special_tokens
																									additional_special_tokens.append('''new_additional_special_token'''			)
																									tokenizer.add_special_tokens({'''additional_special_tokens''': additional_special_tokens}			)
																									__lowerCamelCase      :      int         =tokenizer.encode(__lowercase						,    add_special_tokens=__lowercase			)
																									tokenizer.save_pretrained(__lowercase			)

																									__lowerCamelCase      :      List[Any]         =tokenizer.__class__.from_pretrained(__lowercase			)
																									__lowerCamelCase      :      List[Any]         =after_tokenizer.encode(__lowercase						,    add_special_tokens=__lowercase			)
																									self.assertListEqual(__lowercase						,    __lowercase			)
																									self.assertIn('''new_additional_special_token'''						,    after_tokenizer.additional_special_tokens			)
																									self.assertEqual(after_tokenizer.model_max_length						,    42			)

																									__lowerCamelCase      :      Tuple         =tokenizer.__class__.from_pretrained(__lowercase						,    model_max_length=43			)
																									self.assertEqual(tokenizer.model_max_length						,    43			)

																									shutil.rmtree(__lowercase			)




				def 					__lowercase  (     self  :str			):
											__lowerCamelCase      :      List[str]         =[]
											if self.test_slow_tokenizer:
																		tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())			)

											if self.test_rust_tokenizer:
																		tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())			)

											for tokenizer_class, tokenizer_utils in tokenizer_list:
																		with tempfile.TemporaryDirectory() as tmp_dir:
																									tokenizer_utils.save_pretrained(__lowercase			)

																									with open(os.path.join(__lowercase						,    '''special_tokens_map.json'''			)						,    encoding='''utf-8'''			) as json_file:
																																__lowerCamelCase      :      str         =json.load(__lowercase			)

																									with open(os.path.join(__lowercase						,    '''tokenizer_config.json'''			)						,    encoding='''utf-8'''			) as json_file:
																																__lowerCamelCase      :      List[str]         =json.load(__lowercase			)

																									__lowerCamelCase      :      Any         =[f'<extra_id_{i}>' for i in range(125			)]

																									__lowerCamelCase      :      Optional[int]         =added_tokens_extra_ids + [
																									    '''an_additional_special_token'''
																									]
																									__lowerCamelCase      :      List[str]         =added_tokens_extra_ids + [
																									    '''an_additional_special_token'''
																									]

																									with open(os.path.join(__lowercase						,    '''special_tokens_map.json'''			)						,    '''w'''						,    encoding='''utf-8'''			) as outfile:
																																json.dump(__lowercase						,    __lowercase			)
																									with open(os.path.join(__lowercase						,    '''tokenizer_config.json'''			)						,    '''w'''						,    encoding='''utf-8'''			) as outfile:
																																json.dump(__lowercase						,    __lowercase			)

																									# the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
																									# into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
																									# "special_tokens_map.json" files
																									__lowerCamelCase      :      int         =tokenizer_class.from_pretrained(
																									    __lowercase						,    )
																									self.assertIn(
																									    '''an_additional_special_token'''						,    tokenizer_without_change_in_init.additional_special_tokens			)
																									# self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab
																									self.assertEqual(
																									    ['''an_additional_special_token''']						,    tokenizer_without_change_in_init.convert_ids_to_tokens(
																									        tokenizer_without_change_in_init.convert_tokens_to_ids(['''an_additional_special_token''']			)			)						,    )

																									# Now we test that we can change the value of additional_special_tokens in the from_pretrained
																									__lowerCamelCase      :      int         =added_tokens_extra_ids + [AddedToken('''a_new_additional_special_token'''						,    lstrip=__lowercase			)]
																									__lowerCamelCase      :      List[str]         =tokenizer_class.from_pretrained(
																									    __lowercase						,    additional_special_tokens=__lowercase						,    )

																									self.assertIn('''a_new_additional_special_token'''						,    tokenizer.additional_special_tokens			)
																									self.assertEqual(
																									    ['''a_new_additional_special_token''']						,    tokenizer.convert_ids_to_tokens(
																									        tokenizer.convert_tokens_to_ids(['''a_new_additional_special_token''']			)			)						,    )




				def 					__lowercase  (     self  :int			):
											__lowerCamelCase      :      Dict         =[]
											if self.test_slow_tokenizer:
																		tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())			)

											if self.test_rust_tokenizer:
																		tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())			)

											for tokenizer_class, tokenizer_utils in tokenizer_list:
																		with tempfile.TemporaryDirectory() as tmp_dir:
																									tokenizer_utils.save_pretrained(__lowercase			)

																									__lowerCamelCase      :      Optional[int]         =tokenizer_class.from_pretrained(__lowercase			)

																									self.assertTrue(tokenizer.decode([255]			) == ''''''			)




				def 					__lowercase  (     self  :Dict			):
											pass




				def 					__lowercase  (     self  :Optional[int]			):
											pass




				def 					__lowercase  (     self  :Dict			):
											pass




				def 					__lowercase  (     self  :Dict			):
											pass




				def 					__lowercase  (     self  :Union[str, Any]			):
											# The default common tokenizer tests uses invalid tokens for ByT5 that can only accept one-character strings
											# and special added tokens as tokens
											__lowerCamelCase      :      Optional[int]         =self.get_tokenizers(fast=__lowercase						,    do_lower_case=__lowercase			)
											for tokenizer in tokenizers:
																		with self.subTest(f'{tokenizer.__class__.__name__}'			):
																									__lowerCamelCase      :      Any         =['''t''', '''h''', '''i''', '''s''', ''' ''', '''i''', '''s''', ''' ''', '''a''', ''' ''', '''t''', '''e''', '''x''', '''t''', '''</s>''']
																									__lowerCamelCase      :      Any         =tokenizer.convert_tokens_to_string(__lowercase			)

																									self.assertIsInstance(__lowercase						,    __lowercase			)




				def 					__lowercase  (     self  :str			):
											__lowerCamelCase      :      int         =self.get_tokenizers()
											for tokenizer in tokenizers:
																		with self.subTest(f'{tokenizer.__class__.__name__}'			):
																									__lowerCamelCase      :      List[Any]         =[
																									    '''bos_token''',
																									    '''eos_token''',
																									    '''unk_token''',
																									    '''sep_token''',
																									    '''pad_token''',
																									    '''cls_token''',
																									    '''mask_token''',
																									]

																									__lowerCamelCase      :      Tuple         =0
																									__lowerCamelCase      :      List[str]         =tokenizer.convert_ids_to_tokens(
																									    __lowercase						,    skip_special_tokens=__lowercase			)

																									for attr in attributes_list:
																																setattr(__lowercase						,    attr + '''_id'''						,    __lowercase			)
																																self.assertEqual(getattr(__lowercase						,    __lowercase			)						,    __lowercase			)
																																self.assertEqual(getattr(__lowercase						,    attr + '''_id'''			)						,    __lowercase			)

																																setattr(__lowercase						,    attr + '''_id'''						,    __lowercase			)
																																self.assertEqual(getattr(__lowercase						,    __lowercase			)						,    __lowercase			)
																																self.assertEqual(getattr(__lowercase						,    attr + '''_id'''			)						,    __lowercase			)

																									setattr(__lowercase						,    '''additional_special_tokens_ids'''						,    []			)
																									self.assertListEqual(getattr(__lowercase						,    '''additional_special_tokens'''			)						,    []			)
																									self.assertListEqual(getattr(__lowercase						,    '''additional_special_tokens_ids'''			)						,    []			)

																									setattr(__lowercase						,    '''additional_special_tokens_ids'''						,    [token_id_to_test_setters]			)
																									self.assertListEqual(getattr(__lowercase						,    '''additional_special_tokens'''			)						,    [token_to_test_setters]			)
																									self.assertListEqual(getattr(__lowercase						,    '''additional_special_tokens_ids'''			)						,    [token_id_to_test_setters]			)











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




