


'''simple docstring'''






# 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       							=				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       							=				{'''base''': '''patrickvonplaten/wav2vec2_tiny_random''', '''robust''': '''patrickvonplaten/wav2vec2_tiny_random_robust'''}

__UpperCAmelCase       							=				'''zero2'''
__UpperCAmelCase       							=				'''zero3'''
__UpperCAmelCase       							=				[ZEROa, ZEROa]


def    _snake_case  (	A					,       A					,       A			)		->       List[str]:
							# 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
							lowerCAmelCase__			  =      parameterized.to_safe_name('''_'''.join(str(A			) for x in param.args			)			)
							return F"""{func.__name__}_{param_based_name}"""


# Cartesian-product of zero stages with models to test
__UpperCAmelCase       							=				list(itertools.product(stages, models.keys()))






@slow
@require_deepspeed
@require_torch_gpu
class 						a__							(				a__    ):





							'''simple docstring'''






							@parameterized.expand(lowerCamelCase_   ,       name_func=lowerCamelCase_  )
							def     __SCREAMING_SNAKE_CASE				(						self   ,       lowerCamelCase_   ,       lowerCamelCase_  )			->				Any:
														self.run_and_check(
														    stage=lowerCamelCase_   ,       model=lowerCamelCase_   ,       distributed=lowerCamelCase_   ,       fpaa=lowerCamelCase_   ,       )







							@require_torch_multi_gpu
							@parameterized.expand(lowerCamelCase_   ,       name_func=lowerCamelCase_  )
							def     __SCREAMING_SNAKE_CASE				(						self   ,       lowerCamelCase_   ,       lowerCamelCase_  )			->				int:
														self.run_and_check(
														    stage=lowerCamelCase_   ,       model=lowerCamelCase_   ,       distributed=lowerCamelCase_   ,       fpaa=lowerCamelCase_   ,       )







							@parameterized.expand(lowerCamelCase_   ,       name_func=lowerCamelCase_  )
							def     __SCREAMING_SNAKE_CASE				(						self   ,       lowerCamelCase_   ,       lowerCamelCase_  )			->				Tuple:
														self.run_and_check(
														    stage=lowerCamelCase_   ,       model=lowerCamelCase_   ,       distributed=lowerCamelCase_   ,       fpaa=lowerCamelCase_   ,       )







							@require_torch_multi_gpu
							@parameterized.expand(lowerCamelCase_   ,       name_func=lowerCamelCase_  )
							def     __SCREAMING_SNAKE_CASE				(						self   ,       lowerCamelCase_   ,       lowerCamelCase_  )			->				Optional[int]:
														self.run_and_check(
														    stage=lowerCamelCase_   ,       model=lowerCamelCase_   ,       distributed=lowerCamelCase_   ,       fpaa=lowerCamelCase_   ,       )







							def     __SCREAMING_SNAKE_CASE				(						self   ,       lowerCamelCase_  )			->				Union[str, Any]:
														# XXX: run_asr is premature and doesn't save any results
														# so all we check for now is that the process didn't fail
														pass







							def     __SCREAMING_SNAKE_CASE				(						self   ,       lowerCamelCase_   ,       lowerCamelCase_   ,       lowerCamelCase_ = 10   ,       lowerCamelCase_ = True   ,       lowerCamelCase_ = True   ,       lowerCamelCase_ = True   ,       )			->				Optional[int]:
														lowerCAmelCase__			  =      models[model]

														lowerCAmelCase__			  =      self.run_trainer(
														    stage=lowerCamelCase_   ,       model_name=lowerCamelCase_   ,       eval_steps=lowerCamelCase_   ,       num_train_epochs=1   ,       distributed=lowerCamelCase_   ,       fpaa=lowerCamelCase_   ,       )

														self.do_checks(lowerCamelCase_  )

														return output_dir







							def     __SCREAMING_SNAKE_CASE				(						self   ,       lowerCamelCase_   ,       lowerCamelCase_   ,       lowerCamelCase_ = 10   ,       lowerCamelCase_ = 1   ,       lowerCamelCase_ = True   ,       lowerCamelCase_ = True   ,       )			->				Optional[int]:
														lowerCAmelCase__			  =      self.get_auto_remove_tmp_dir('''./xxx'''   ,       after=lowerCamelCase_  )
														lowerCAmelCase__			  =      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(lowerCamelCase_  )}
            --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
														lowerCAmelCase__			  =      F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split()
														lowerCAmelCase__			  =      [F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""]
														lowerCAmelCase__			  =      self.get_launcher(lowerCamelCase_  )

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

														return output_dir







							def     __SCREAMING_SNAKE_CASE				(						self   ,       lowerCamelCase_=False  )			->				Any:
														# 1. explicitly set --num_nodes=1 just in case these tests end up run on a multi-node setup
														# - it won't be able to handle that
														# 2. for now testing with just 2 gpus max (since some quality tests may give different
														# results with mode gpus because we use very little data)
														lowerCAmelCase__			  =      min(2   ,       get_gpu_count()  ) if distributed else 1
														return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()



'''simple docstring'''






import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


__UpperCAmelCase       							=				False




class 						a__							(				unittest.TestCase    ):





							'''simple docstring'''






							pass




@nightly
@require_torch_gpu
class 						a__							(				unittest.TestCase    ):





							'''simple docstring'''






							def     __SCREAMING_SNAKE_CASE				(						self  )			->				List[Any]:
														# clean up the VRAM after each test
														super().tearDown()
														gc.collect()
														torch.cuda.empty_cache()







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Optional[int]:
														lowerCAmelCase__			  =      VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion'''   ,       torch_dtype=torch.floataa  )
														pipe.to(lowerCamelCase_  )
														pipe.set_progress_bar_config(disable=lowerCamelCase_  )

														lowerCAmelCase__			  =      load_image(
														    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'''  )

														lowerCAmelCase__			  =      torch.manual_seed(0  )
														lowerCAmelCase__			  =      pipe.dual_guided(
														    prompt='''first prompt'''   ,       image=lowerCamelCase_   ,       text_to_image_strength=0.75   ,       generator=lowerCamelCase_   ,       guidance_scale=7.5   ,       num_inference_steps=2   ,       output_type='''numpy'''   ,       ).images

														with tempfile.TemporaryDirectory() as tmpdirname:
																					pipe.save_pretrained(lowerCamelCase_  )
																					lowerCAmelCase__			  =      VersatileDiffusionPipeline.from_pretrained(lowerCamelCase_   ,       torch_dtype=torch.floataa  )
														pipe.to(lowerCamelCase_  )
														pipe.set_progress_bar_config(disable=lowerCamelCase_  )

														lowerCAmelCase__			  =      generator.manual_seed(0  )
														lowerCAmelCase__			  =      pipe.dual_guided(
														    prompt='''first prompt'''   ,       image=lowerCamelCase_   ,       text_to_image_strength=0.75   ,       generator=lowerCamelCase_   ,       guidance_scale=7.5   ,       num_inference_steps=2   ,       output_type='''numpy'''   ,       ).images

														assert np.abs(image - new_image  ).sum() < 1e-5, "Models don't have the same forward pass"







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Optional[Any]:
														lowerCAmelCase__			  =      VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion'''   ,       torch_dtype=torch.floataa  )
														pipe.to(lowerCamelCase_  )
														pipe.set_progress_bar_config(disable=lowerCamelCase_  )

														lowerCAmelCase__			  =      '''cyberpunk 2077'''
														lowerCAmelCase__			  =      load_image(
														    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'''  )
														lowerCAmelCase__			  =      torch.manual_seed(0  )
														lowerCAmelCase__			  =      pipe.dual_guided(
														    prompt=lowerCamelCase_   ,       image=lowerCamelCase_   ,       text_to_image_strength=0.75   ,       generator=lowerCamelCase_   ,       guidance_scale=7.5   ,       num_inference_steps=50   ,       output_type='''numpy'''   ,       ).images

														lowerCAmelCase__			  =      image[0, 2_53:2_56, 2_53:2_56, -1]

														assert image.shape == (1, 5_12, 5_12, 3)
														lowerCAmelCase__			  =      np.array([0.1_448, 0.1_619, 0.1_741, 0.1_086, 0.1_147, 0.1_128, 0.1_199, 0.1_165, 0.1_001]  )

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

														lowerCAmelCase__			  =      '''A painting of a squirrel eating a burger '''
														lowerCAmelCase__			  =      torch.manual_seed(0  )
														lowerCAmelCase__			  =      pipe.text_to_image(
														    prompt=lowerCamelCase_   ,       generator=lowerCamelCase_   ,       guidance_scale=7.5   ,       num_inference_steps=50   ,       output_type='''numpy'''  ).images

														lowerCAmelCase__			  =      image[0, 2_53:2_56, 2_53:2_56, -1]

														assert image.shape == (1, 5_12, 5_12, 3)
														lowerCAmelCase__			  =      np.array([0.3_367, 0.3_169, 0.2_656, 0.3_870, 0.4_790, 0.3_796, 0.4_009, 0.4_878, 0.4_778]  )

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

														lowerCAmelCase__			  =      pipe.image_variation(lowerCamelCase_   ,       generator=lowerCamelCase_   ,       output_type='''numpy'''  ).images

														lowerCAmelCase__			  =      image[0, 2_53:2_56, 2_53:2_56, -1]

														assert image.shape == (1, 5_12, 5_12, 3)
														lowerCAmelCase__			  =      np.array([0.3_076, 0.3_123, 0.3_284, 0.3_782, 0.3_770, 0.3_894, 0.4_297, 0.4_331, 0.4_456]  )

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