# XXX: we want transformers master here - in the absense of conftest manipulating sys.path:
# hack it in for now:
import sys
from pathlib import Path


__UpperCamelCase	: Optional[Any]    		=  Path(__file__).resolve().parents[3] / 'src'
sys.path.insert(1, str(git_repo_path))

import dataclasses  # noqa
import io  # noqa
import itertools  # noqa
import json  # noqa
import os  # noqa
import unittest  # noqa
from copy import deepcopy  # noqa

from parameterized import parameterized  # noqa
from transformers import TrainingArguments, is_torch_available  # noqa
from transformers.deepspeed import is_deepspeed_available  # noqa
from transformers.file_utils import WEIGHTS_NAME  # noqa
from transformers.testing_utils import (  # noqa
    CaptureLogger,
    ExtendSysPath,
    TestCasePlus,
    execute_subprocess_async,
    get_gpu_count,
    mockenv_context,
    require_deepspeed,
    require_torch_gpu,
    require_torch_multi_gpu,
    slow,
)
from transformers.trainer_utils import set_seed  # noqa


set_seed(42)

__UpperCamelCase	: str    		=  {'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'}

__UpperCamelCase	: List[str]    		=  'zero2'
__UpperCamelCase	: Any    		=  'zero3'
__UpperCamelCase	: Any    		=  [ZEROa, ZEROa]
def    A			(					_lowercase	,						_lowercase	,						_lowercase		):
						# customize the test name generator function as we want both params to appear in the sub-test
						# name, as by default it shows only the first param
						SCREAMING_SNAKE_CASE							:					int           =							parameterized.to_safe_name('''_'''.join(str(_lowercase		) for x in param.args		)		)
						return f"""{func.__name__}_{param_based_name}"""


# Cartesian-product of zero stages with models to test
__UpperCamelCase	: Optional[int]    		=  list(itertools.product(stages, models.keys()))





@slow
@require_deepspeed
@require_torch_gpu
class       lowercase__		(     UpperCamelCase_):


						@parameterized.expand(UpperCamelCase__					,	name_func=UpperCamelCase__		)
						def  __A ( self			:       Union[str, Any]					,	UpperCamelCase__			:       List[Any]					,	UpperCamelCase__			:       int		):





												'''simple docstring'''





												self.run_and_check(
												    stage=UpperCamelCase__					,	model=UpperCamelCase__					,	distributed=UpperCamelCase__					,	fpaa=UpperCamelCase__					,	)


						@require_torch_multi_gpu
						@parameterized.expand(UpperCamelCase__					,	name_func=UpperCamelCase__		)
						def  __A ( self			:       List[str]					,	UpperCamelCase__			:       Tuple					,	UpperCamelCase__			:       int		):





												'''simple docstring'''





												self.run_and_check(
												    stage=UpperCamelCase__					,	model=UpperCamelCase__					,	distributed=UpperCamelCase__					,	fpaa=UpperCamelCase__					,	)


						@parameterized.expand(UpperCamelCase__					,	name_func=UpperCamelCase__		)
						def  __A ( self			:       Dict					,	UpperCamelCase__			:       Optional[Any]					,	UpperCamelCase__			:       Any		):





												'''simple docstring'''





												self.run_and_check(
												    stage=UpperCamelCase__					,	model=UpperCamelCase__					,	distributed=UpperCamelCase__					,	fpaa=UpperCamelCase__					,	)


						@require_torch_multi_gpu
						@parameterized.expand(UpperCamelCase__					,	name_func=UpperCamelCase__		)
						def  __A ( self			:       Dict					,	UpperCamelCase__			:       Optional[Any]					,	UpperCamelCase__			:       str		):





												'''simple docstring'''





												self.run_and_check(
												    stage=UpperCamelCase__					,	model=UpperCamelCase__					,	distributed=UpperCamelCase__					,	fpaa=UpperCamelCase__					,	)


						def  __A ( self			:       Optional[Any]					,	UpperCamelCase__			:       Tuple		):





												'''simple docstring'''





												pass


						def  __A ( self			:       Tuple					,	UpperCamelCase__			:       str					,	UpperCamelCase__			:       str					,	UpperCamelCase__			:       int = 10					,	UpperCamelCase__			:       bool = True					,	UpperCamelCase__			:       bool = True					,	UpperCamelCase__			:       bool = True					,	):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					str           =							models[model]

												SCREAMING_SNAKE_CASE							:					Optional[int]           =							self.run_trainer(
												    stage=UpperCamelCase__					,	model_name=UpperCamelCase__					,	eval_steps=UpperCamelCase__					,	num_train_epochs=1					,	distributed=UpperCamelCase__					,	fpaa=UpperCamelCase__					,	)

												self.do_checks(UpperCamelCase__		)

												return output_dir


						def  __A ( self			:       str					,	UpperCamelCase__			:       str					,	UpperCamelCase__			:       str					,	UpperCamelCase__			:       int = 10					,	UpperCamelCase__			:       int = 1					,	UpperCamelCase__			:       bool = True					,	UpperCamelCase__			:       bool = True					,	):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					str           =							self.get_auto_remove_tmp_dir('''./xxx'''					,	after=UpperCamelCase__		)
												SCREAMING_SNAKE_CASE							:					Optional[int]           =							f"""
            --model_name_or_path {model_name}
            --dataset_name hf-internal-testing/librispeech_asr_dummy
            --dataset_config_name clean
            --train_split_name validation
            --validation_split_name validation
            --output_dir {output_dir}
            --num_train_epochs {str(UpperCamelCase__		)}
            --per_device_train_batch_size 2
            --per_device_eval_batch_size 2
            --evaluation_strategy steps
            --learning_rate 5e-4
            --warmup_steps 8
            --orthography timit
            --preprocessing_num_workers 1
            --group_by_length
            --freeze_feature_extractor
            --report_to none
            --save_steps 0
            --eval_steps {eval_steps}
            --report_to none
        """.split()

												if fpaa:
																		args.extend(['''--fp16''']		)

												# currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true,
												# hence the separate config files
												SCREAMING_SNAKE_CASE							:					Optional[int]           =							f"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split()
												SCREAMING_SNAKE_CASE							:					Optional[int]           =							[f"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""]
												SCREAMING_SNAKE_CASE							:					List[str]           =							self.get_launcher(UpperCamelCase__		)

												SCREAMING_SNAKE_CASE							:					Tuple           =							launcher + script + args + ds_args
												# keep for quick debug
												# print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
												execute_subprocess_async(UpperCamelCase__					,	env=self.get_env()		)

												return output_dir



						def  __A ( self			:       Any					,	UpperCamelCase__			:       Any=False		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					int           =							min(2					,	get_gpu_count()		) if distributed else 1
												return f"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()






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       lowercase__		(     UpperCamelCase_			,							UpperCamelCase_			,							unittest.TestCase):
						UpperCamelCase_  =	IFPipeline
						UpperCamelCase_  =	TEXT_TO_IMAGE_PARAMS - {"""width""", """height""", """latents"""}
						UpperCamelCase_  =	TEXT_TO_IMAGE_BATCH_PARAMS
						UpperCamelCase_  =	PipelineTesterMixin.required_optional_params - {"""latents"""}


						def  __A ( self			:       Tuple		):





												'''simple docstring'''





												return self._get_dummy_components()


						def  __A ( self			:       int					,	UpperCamelCase__			:       Dict					,	UpperCamelCase__			:       int=0		):





												'''simple docstring'''





												if str(UpperCamelCase__		).startswith('''mps'''		):
																		SCREAMING_SNAKE_CASE							:					Tuple           =							torch.manual_seed(UpperCamelCase__		)
												else:
																		SCREAMING_SNAKE_CASE							:					Dict           =							torch.Generator(device=UpperCamelCase__		).manual_seed(UpperCamelCase__		)

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

												return inputs


						def  __A ( self			:       List[str]		):





												'''simple docstring'''





												self._test_save_load_optional_components()


						@unittest.skipIf(torch_device != '''cuda'''					,	reason='''float16 requires CUDA'''		)
						def  __A ( self			:       Any		):





												'''simple docstring'''





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


						def  __A ( self			:       Union[str, Any]		):





												'''simple docstring'''





												self._test_attention_slicing_forward_pass(expected_max_diff=1E-2		)


						def  __A ( self			:       List[Any]		):





												'''simple docstring'''





												self._test_save_load_local()


						def  __A ( self			:       List[str]		):





												'''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  __A ( self			:       Tuple		):





												'''simple docstring'''





												self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3		)






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


						def  __A ( self			:       Optional[Any]		):





												'''simple docstring'''





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


						def  __A ( self			:       Union[str, Any]		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							IFPipeline.from_pretrained('''DeepFloyd/IF-I-XL-v1.0'''					,	variant='''fp16'''					,	torch_dtype=torch.floataa		)

												SCREAMING_SNAKE_CASE							:					str           =							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'''		)

												SCREAMING_SNAKE_CASE       ,						SCREAMING_SNAKE_CASE							:					Dict           =							pipe_a.encode_prompt('''anime turtle'''					,	device='''cuda'''		)

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

												SCREAMING_SNAKE_CASE							:					Tuple           =							None
												SCREAMING_SNAKE_CASE							:					str           =							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

												SCREAMING_SNAKE_CASE							:					Optional[int]           =							IFImgaImgPipeline(**pipe_a.components		)
												SCREAMING_SNAKE_CASE							:					Optional[int]           =							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

												SCREAMING_SNAKE_CASE							:					Tuple           =							IFInpaintingPipeline(**pipe_a.components		)
												SCREAMING_SNAKE_CASE							:					Optional[int]           =							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  __A ( self			:       Tuple					,	UpperCamelCase__			:       int					,	UpperCamelCase__			:       Union[str, Any]					,	UpperCamelCase__			:       Union[str, Any]					,	UpperCamelCase__			:       Dict		):





												'''simple docstring'''





												_start_torch_memory_measurement()

												SCREAMING_SNAKE_CASE							:					List[str]           =							torch.Generator(device='''cpu'''		).manual_seed(0		)
												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							pipe_a(
												    prompt_embeds=UpperCamelCase__					,	negative_prompt_embeds=UpperCamelCase__					,	num_inference_steps=2					,	generator=UpperCamelCase__					,	output_type='''np'''					,	)

												SCREAMING_SNAKE_CASE							:					Optional[int]           =							output.images[0]

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

												SCREAMING_SNAKE_CASE							:					Tuple           =							torch.cuda.max_memory_allocated()
												assert mem_bytes < 13 * 10**9

												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							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()

												SCREAMING_SNAKE_CASE							:					Tuple           =							torch.Generator(device='''cpu'''		).manual_seed(0		)

												SCREAMING_SNAKE_CASE							:					int           =							floats_tensor((1, 3, 64, 64)					,	rng=random.Random(0		)		).to(UpperCamelCase__		)

												SCREAMING_SNAKE_CASE							:					Any           =							pipe_a(
												    prompt_embeds=UpperCamelCase__					,	negative_prompt_embeds=UpperCamelCase__					,	image=UpperCamelCase__					,	generator=UpperCamelCase__					,	num_inference_steps=2					,	output_type='''np'''					,	)

												SCREAMING_SNAKE_CASE							:					Tuple           =							output.images[0]

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

												SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							torch.cuda.max_memory_allocated()
												assert mem_bytes < 4 * 10**9

												SCREAMING_SNAKE_CASE							:					int           =							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  __A ( self			:       Optional[int]					,	UpperCamelCase__			:       str					,	UpperCamelCase__			:       int					,	UpperCamelCase__			:       Optional[Any]					,	UpperCamelCase__			:       str		):





												'''simple docstring'''





												_start_torch_memory_measurement()

												SCREAMING_SNAKE_CASE							:					Tuple           =							floats_tensor((1, 3, 64, 64)					,	rng=random.Random(0		)		).to(UpperCamelCase__		)

												SCREAMING_SNAKE_CASE							:					Any           =							torch.Generator(device='''cpu'''		).manual_seed(0		)

												SCREAMING_SNAKE_CASE							:					List[Any]           =							pipe_a(
												    prompt_embeds=UpperCamelCase__					,	negative_prompt_embeds=UpperCamelCase__					,	image=UpperCamelCase__					,	num_inference_steps=2					,	generator=UpperCamelCase__					,	output_type='''np'''					,	)

												SCREAMING_SNAKE_CASE							:					int           =							output.images[0]

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

												SCREAMING_SNAKE_CASE							:					Optional[int]           =							torch.cuda.max_memory_allocated()
												assert mem_bytes < 10 * 10**9

												SCREAMING_SNAKE_CASE							:					Tuple           =							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()

												SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							torch.Generator(device='''cpu'''		).manual_seed(0		)

												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							floats_tensor((1, 3, 256, 256)					,	rng=random.Random(0		)		).to(UpperCamelCase__		)
												SCREAMING_SNAKE_CASE							:					List[Any]           =							floats_tensor((1, 3, 64, 64)					,	rng=random.Random(0		)		).to(UpperCamelCase__		)

												SCREAMING_SNAKE_CASE							:					str           =							pipe_a(
												    prompt_embeds=UpperCamelCase__					,	negative_prompt_embeds=UpperCamelCase__					,	image=UpperCamelCase__					,	original_image=UpperCamelCase__					,	generator=UpperCamelCase__					,	num_inference_steps=2					,	output_type='''np'''					,	)

												SCREAMING_SNAKE_CASE							:					Optional[int]           =							output.images[0]

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

												SCREAMING_SNAKE_CASE							:					List[Any]           =							torch.cuda.max_memory_allocated()
												assert mem_bytes < 4 * 10**9

												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							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  __A ( self			:       List[str]					,	UpperCamelCase__			:       Optional[int]					,	UpperCamelCase__			:       Optional[int]					,	UpperCamelCase__			:       Union[str, Any]					,	UpperCamelCase__			:       Optional[Any]		):





												'''simple docstring'''





												_start_torch_memory_measurement()

												SCREAMING_SNAKE_CASE							:					str           =							floats_tensor((1, 3, 64, 64)					,	rng=random.Random(0		)		).to(UpperCamelCase__		)
												SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							floats_tensor((1, 3, 64, 64)					,	rng=random.Random(1		)		).to(UpperCamelCase__		)

												SCREAMING_SNAKE_CASE							:					Optional[int]           =							torch.Generator(device='''cpu'''		).manual_seed(0		)
												SCREAMING_SNAKE_CASE							:					int           =							pipe_a(
												    prompt_embeds=UpperCamelCase__					,	negative_prompt_embeds=UpperCamelCase__					,	image=UpperCamelCase__					,	mask_image=UpperCamelCase__					,	num_inference_steps=2					,	generator=UpperCamelCase__					,	output_type='''np'''					,	)

												SCREAMING_SNAKE_CASE							:					Any           =							output.images[0]

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

												SCREAMING_SNAKE_CASE							:					Any           =							torch.cuda.max_memory_allocated()
												assert mem_bytes < 10 * 10**9

												SCREAMING_SNAKE_CASE							:					List[Any]           =							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()

												SCREAMING_SNAKE_CASE							:					str           =							torch.Generator(device='''cpu'''		).manual_seed(0		)

												SCREAMING_SNAKE_CASE							:					List[str]           =							floats_tensor((1, 3, 64, 64)					,	rng=random.Random(0		)		).to(UpperCamelCase__		)
												SCREAMING_SNAKE_CASE							:					int           =							floats_tensor((1, 3, 256, 256)					,	rng=random.Random(0		)		).to(UpperCamelCase__		)
												SCREAMING_SNAKE_CASE							:					Optional[int]           =							floats_tensor((1, 3, 256, 256)					,	rng=random.Random(1		)		).to(UpperCamelCase__		)

												SCREAMING_SNAKE_CASE							:					Dict           =							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'''					,	)

												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							output.images[0]

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

												SCREAMING_SNAKE_CASE							:					Any           =							torch.cuda.max_memory_allocated()
												assert mem_bytes < 4 * 10**9

												SCREAMING_SNAKE_CASE							:					Tuple           =							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    A			(					):
						torch.cuda.empty_cache()
						torch.cuda.reset_max_memory_allocated()
						torch.cuda.reset_peak_memory_stats()





