

import gc
import random
import unittest

import torch

from diffusers import (
    IFImgaImgPipeline,
    IFImgaImgSuperResolutionPipeline,
    IFInpaintingPipeline,
    IFInpaintingSuperResolutionPipeline,
    IFPipeline,
    IFSuperResolutionPipeline,
)
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device

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

@skip_mps
class 				__UpperCamelCase				(					SCREAMING_SNAKE_CASE  ,						SCREAMING_SNAKE_CASE  ,						unittest.TestCase			):
	_lowercase  :   Union[str, Any]       				=  IFPipeline
	_lowercase  :   str       				=  TEXT_TO_IMAGE_PARAMS - {"width", "height", "latents"}
	_lowercase  :   Optional[int]       				=  TEXT_TO_IMAGE_BATCH_PARAMS
	_lowercase  :   Optional[int]       				=  PipelineTesterMixin.required_optional_params - {"latents"}







	def 	_SCREAMING_SNAKE_CASE							(   self: Any      ):

						'''simple docstring'''





						return self._get_dummy_components()







	def 	_SCREAMING_SNAKE_CASE							(   self: Tuple  , __UpperCamelCase: int  , __UpperCamelCase: Optional[Any]=0      ):

						'''simple docstring'''





						if str(__UpperCamelCase      ).startswith('mps'      ):
											__magic_name__							=    torch.manual_seed(__UpperCamelCase      )
						else:
											__magic_name__							=    torch.Generator(device=__UpperCamelCase      ).manual_seed(__UpperCamelCase      )

						__magic_name__							=    {
						    'prompt': 'A painting of a squirrel eating a burger',
						    'generator': generator,
						    'num_inference_steps': 2,
						    'output_type': 'numpy',
						}

						return inputs







	def 	_SCREAMING_SNAKE_CASE							(   self: Tuple      ):

						'''simple docstring'''





						self._test_save_load_optional_components()







	@unittest.skipIf(torch_device != 'cuda'  , reason='float16 requires CUDA'      )
	def 	_SCREAMING_SNAKE_CASE							(   self: List[str]      ):

						'''simple docstring'''





						super().test_save_load_floataa(expected_max_diff=1E-1      )







	def 	_SCREAMING_SNAKE_CASE							(   self: Tuple      ):

						'''simple docstring'''





						self._test_attention_slicing_forward_pass(expected_max_diff=1E-2      )







	def 	_SCREAMING_SNAKE_CASE							(   self: Tuple      ):

						'''simple docstring'''





						self._test_save_load_local()







	def 	_SCREAMING_SNAKE_CASE							(   self: List[Any]      ):

						'''simple docstring'''





						self._test_inference_batch_single_identical(
						    expected_max_diff=1E-2  , )







	@unittest.skipIf(
	    torch_device != 'cuda' or not is_xformers_available()  , reason='XFormers attention is only available with CUDA and `xformers` installed'  , )
	def 	_SCREAMING_SNAKE_CASE							(   self: Optional[int]      ):

						'''simple docstring'''





						self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3      )




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







	def 	_SCREAMING_SNAKE_CASE							(   self: str      ):

						'''simple docstring'''





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







	def 	_SCREAMING_SNAKE_CASE							(   self: int      ):

						'''simple docstring'''





						__magic_name__							=    IFPipeline.from_pretrained('DeepFloyd/IF-I-XL-v1.0'  , variant='fp16'  , torch_dtype=torch.floataa      )

						__magic_name__							=    IFSuperResolutionPipeline.from_pretrained(
						    'DeepFloyd/IF-II-L-v1.0'  , variant='fp16'  , torch_dtype=torch.floataa  , text_encoder=__UpperCamelCase  , tokenizer=__UpperCamelCase      )

						# pre compute text embeddings and remove T5 to save memory

						pipe_a.text_encoder.to('cuda'      )

						__magic_name__,	__magic_name__							=    pipe_a.encode_prompt('anime turtle'  , device='cuda'      )

						del pipe_a.tokenizer
						del pipe_a.text_encoder
						gc.collect()

						__magic_name__							=    None
						__magic_name__							=    None

						pipe_a.enable_model_cpu_offload()
						pipe_a.enable_model_cpu_offload()

						pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()      )
						pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()      )

						self._test_if(__UpperCamelCase  , __UpperCamelCase  , __UpperCamelCase  , __UpperCamelCase      )

						pipe_a.remove_all_hooks()
						pipe_a.remove_all_hooks()

						# img2img

						__magic_name__							=    IFImgaImgPipeline(**pipe_a.components      )
						__magic_name__							=    IFImgaImgSuperResolutionPipeline(**pipe_a.components      )

						pipe_a.enable_model_cpu_offload()
						pipe_a.enable_model_cpu_offload()

						pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()      )
						pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()      )

						self._test_if_imgaimg(__UpperCamelCase  , __UpperCamelCase  , __UpperCamelCase  , __UpperCamelCase      )

						pipe_a.remove_all_hooks()
						pipe_a.remove_all_hooks()

						# inpainting

						__magic_name__							=    IFInpaintingPipeline(**pipe_a.components      )
						__magic_name__							=    IFInpaintingSuperResolutionPipeline(**pipe_a.components      )

						pipe_a.enable_model_cpu_offload()
						pipe_a.enable_model_cpu_offload()

						pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()      )
						pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()      )

						self._test_if_inpainting(__UpperCamelCase  , __UpperCamelCase  , __UpperCamelCase  , __UpperCamelCase      )







	def 	_SCREAMING_SNAKE_CASE							(   self: Any  , __UpperCamelCase: Union[str, Any]  , __UpperCamelCase: List[Any]  , __UpperCamelCase: List[Any]  , __UpperCamelCase: int      ):

						'''simple docstring'''





						_start_torch_memory_measurement()

						__magic_name__							=    torch.Generator(device='cpu'      ).manual_seed(0      )
						__magic_name__							=    pipe_a(
						    prompt_embeds=__UpperCamelCase  , negative_prompt_embeds=__UpperCamelCase  , num_inference_steps=2  , generator=__UpperCamelCase  , output_type='np'  , )

						__magic_name__							=    output.images[0]

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

						__magic_name__							=    torch.cuda.max_memory_allocated()
						assert mem_bytes < 13 * 10**9

						__magic_name__							=    load_numpy(
						    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy'      )
						assert_mean_pixel_difference(__UpperCamelCase  , __UpperCamelCase      )

						# pipeline 2

						_start_torch_memory_measurement()

						__magic_name__							=    torch.Generator(device='cpu'      ).manual_seed(0      )

						__magic_name__							=    floats_tensor((1, 3, 64, 64)  , rng=random.Random(0      )      ).to(__UpperCamelCase      )

						__magic_name__							=    pipe_a(
						    prompt_embeds=__UpperCamelCase  , negative_prompt_embeds=__UpperCamelCase  , image=__UpperCamelCase  , generator=__UpperCamelCase  , num_inference_steps=2  , output_type='np'  , )

						__magic_name__							=    output.images[0]

						assert image.shape == (2_56, 2_56, 3)

						__magic_name__							=    torch.cuda.max_memory_allocated()
						assert mem_bytes < 4 * 10**9

						__magic_name__							=    load_numpy(
						    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy'      )
						assert_mean_pixel_difference(__UpperCamelCase  , __UpperCamelCase      )







	def 	_SCREAMING_SNAKE_CASE							(   self: List[Any]  , __UpperCamelCase: int  , __UpperCamelCase: int  , __UpperCamelCase: Optional[Any]  , __UpperCamelCase: Optional[Any]      ):

						'''simple docstring'''





						_start_torch_memory_measurement()

						__magic_name__							=    floats_tensor((1, 3, 64, 64)  , rng=random.Random(0      )      ).to(__UpperCamelCase      )

						__magic_name__							=    torch.Generator(device='cpu'      ).manual_seed(0      )

						__magic_name__							=    pipe_a(
						    prompt_embeds=__UpperCamelCase  , negative_prompt_embeds=__UpperCamelCase  , image=__UpperCamelCase  , num_inference_steps=2  , generator=__UpperCamelCase  , output_type='np'  , )

						__magic_name__							=    output.images[0]

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

						__magic_name__							=    torch.cuda.max_memory_allocated()
						assert mem_bytes < 10 * 10**9

						__magic_name__							=    load_numpy(
						    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy'      )
						assert_mean_pixel_difference(__UpperCamelCase  , __UpperCamelCase      )

						# pipeline 2

						_start_torch_memory_measurement()

						__magic_name__							=    torch.Generator(device='cpu'      ).manual_seed(0      )

						__magic_name__							=    floats_tensor((1, 3, 2_56, 2_56)  , rng=random.Random(0      )      ).to(__UpperCamelCase      )
						__magic_name__							=    floats_tensor((1, 3, 64, 64)  , rng=random.Random(0      )      ).to(__UpperCamelCase      )

						__magic_name__							=    pipe_a(
						    prompt_embeds=__UpperCamelCase  , negative_prompt_embeds=__UpperCamelCase  , image=__UpperCamelCase  , original_image=__UpperCamelCase  , generator=__UpperCamelCase  , num_inference_steps=2  , output_type='np'  , )

						__magic_name__							=    output.images[0]

						assert image.shape == (2_56, 2_56, 3)

						__magic_name__							=    torch.cuda.max_memory_allocated()
						assert mem_bytes < 4 * 10**9

						__magic_name__							=    load_numpy(
						    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy'      )
						assert_mean_pixel_difference(__UpperCamelCase  , __UpperCamelCase      )







	def 	_SCREAMING_SNAKE_CASE							(   self: Dict  , __UpperCamelCase: int  , __UpperCamelCase: List[str]  , __UpperCamelCase: Tuple  , __UpperCamelCase: Dict      ):

						'''simple docstring'''





						_start_torch_memory_measurement()

						__magic_name__							=    floats_tensor((1, 3, 64, 64)  , rng=random.Random(0      )      ).to(__UpperCamelCase      )
						__magic_name__							=    floats_tensor((1, 3, 64, 64)  , rng=random.Random(1      )      ).to(__UpperCamelCase      )

						__magic_name__							=    torch.Generator(device='cpu'      ).manual_seed(0      )
						__magic_name__							=    pipe_a(
						    prompt_embeds=__UpperCamelCase  , negative_prompt_embeds=__UpperCamelCase  , image=__UpperCamelCase  , mask_image=__UpperCamelCase  , num_inference_steps=2  , generator=__UpperCamelCase  , output_type='np'  , )

						__magic_name__							=    output.images[0]

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

						__magic_name__							=    torch.cuda.max_memory_allocated()
						assert mem_bytes < 10 * 10**9

						__magic_name__							=    load_numpy(
						    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy'      )
						assert_mean_pixel_difference(__UpperCamelCase  , __UpperCamelCase      )

						# pipeline 2

						_start_torch_memory_measurement()

						__magic_name__							=    torch.Generator(device='cpu'      ).manual_seed(0      )

						__magic_name__							=    floats_tensor((1, 3, 64, 64)  , rng=random.Random(0      )      ).to(__UpperCamelCase      )
						__magic_name__							=    floats_tensor((1, 3, 2_56, 2_56)  , rng=random.Random(0      )      ).to(__UpperCamelCase      )
						__magic_name__							=    floats_tensor((1, 3, 2_56, 2_56)  , rng=random.Random(1      )      ).to(__UpperCamelCase      )

						__magic_name__							=    pipe_a(
						    prompt_embeds=__UpperCamelCase  , negative_prompt_embeds=__UpperCamelCase  , image=__UpperCamelCase  , mask_image=__UpperCamelCase  , original_image=__UpperCamelCase  , generator=__UpperCamelCase  , num_inference_steps=2  , output_type='np'  , )

						__magic_name__							=    output.images[0]

						assert image.shape == (2_56, 2_56, 3)

						__magic_name__							=    torch.cuda.max_memory_allocated()
						assert mem_bytes < 4 * 10**9

						__magic_name__							=    load_numpy(
						    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy'      )
						assert_mean_pixel_difference(__UpperCamelCase  , __UpperCamelCase      )




def 					_lowercase     (				)				->	Tuple:




					'''simple docstring'''







					torch.cuda.empty_cache()
					torch.cuda.reset_max_memory_allocated()
					torch.cuda.reset_peak_memory_stats()







import os
import unittest

from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast
from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin

@require_tokenizers
class 				__UpperCamelCase				(					SCREAMING_SNAKE_CASE  ,						unittest.TestCase			):
	_lowercase  :   Tuple       				=  LayoutLMTokenizer
	_lowercase  :   List[str]       				=  LayoutLMTokenizerFast
	_lowercase  :   List[Any]       				=  True
	_lowercase  :   Optional[int]       				=  True







	def 	_SCREAMING_SNAKE_CASE							(   self: Any      ):

						'''simple docstring'''





						super().setUp()

						__magic_name__							=    [
						    '[UNK]',
						    '[CLS]',
						    '[SEP]',
						    'want',
						    '##want',
						    '##ed',
						    'wa',
						    'un',
						    'runn',
						    '##ing',
						    ',',
						    'low',
						    'lowest',
						]
						__magic_name__							=    os.path.join(self.tmpdirname  , VOCAB_FILES_NAMES['vocab_file']      )
						with open(self.vocab_file  , 'w'  , encoding='utf-8'      ) as vocab_writer:
											vocab_writer.write(''.join([x + '\n' for x in vocab_tokens]      )      )







	def 	_SCREAMING_SNAKE_CASE							(   self: Union[str, Any]  , **__UpperCamelCase: Union[str, Any]      ):

						'''simple docstring'''





						return LayoutLMTokenizer.from_pretrained(self.tmpdirname  , **__UpperCamelCase      )







	def 	_SCREAMING_SNAKE_CASE							(   self: Tuple  , __UpperCamelCase: List[str]      ):

						'''simple docstring'''





						__magic_name__							=    'UNwant\u00E9d,running'
						__magic_name__							=    'unwanted, running'
						return input_text, output_text







	def 	_SCREAMING_SNAKE_CASE							(   self: List[Any]      ):

						'''simple docstring'''





						__magic_name__							=    self.tokenizer_class(self.vocab_file      )

						__magic_name__							=    tokenizer.tokenize('UNwant\u00E9d,running'      )
						self.assertListEqual(__UpperCamelCase  , ['un', '##want', '##ed', ',', 'runn', '##ing']      )
						self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCamelCase      )  , [7, 4, 5, 10, 8, 9]      )







	def 	_SCREAMING_SNAKE_CASE							(   self: Dict      ):

						'''simple docstring'''





						pass




