


"""simple docstring"""





import tempfile

import numpy as np
import torch
from transformers import AutoTokenizer, TaEncoderModel

from diffusers import DDPMScheduler, UNetaDConditionModel
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.pipelines.deepfloyd_if import IFWatermarker
from diffusers.utils.testing_utils import torch_device

from ..test_pipelines_common import to_np
class 				lowercase__       :







       '''simple docstring'''


       def 					lowercase__    (							self      :  int   )			->						Union[str, Any]:


             '''simple docstring'''




             torch.manual_seed(0   )
             UpperCAmelCase_      			=							TaEncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5"   )

             torch.manual_seed(0   )
             UpperCAmelCase_      			=							AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5"   )

             torch.manual_seed(0   )
             UpperCAmelCase_      			=							UNetaDConditionModel(
                 sample_size=32		,    layers_per_block=1		,    block_out_channels=[32, 64]		,    down_block_types=[
                     "ResnetDownsampleBlock2D",
                     "SimpleCrossAttnDownBlock2D",
                 ]		,    mid_block_type="UNetMidBlock2DSimpleCrossAttn"		,    up_block_types=["SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"]		,    in_channels=3		,    out_channels=6		,    cross_attention_dim=32		,    encoder_hid_dim=32		,    attention_head_dim=8		,    addition_embed_type="text"		,    addition_embed_type_num_heads=2		,    cross_attention_norm="group_norm"		,    resnet_time_scale_shift="scale_shift"		,    act_fn="gelu"		,    )
             unet.set_attn_processor(AttnAddedKVProcessor()   )  # For reproducibility tests

             torch.manual_seed(0   )
             UpperCAmelCase_      			=							DDPMScheduler(
                 num_train_timesteps=1000		,    beta_schedule="squaredcos_cap_v2"		,    beta_start=0.0001		,    beta_end=0.02		,    thresholding=_UpperCAmelCase		,    dynamic_thresholding_ratio=0.95		,    sample_max_value=1.0		,    prediction_type="epsilon"		,    variance_type="learned_range"		,    )

             torch.manual_seed(0   )
             UpperCAmelCase_      			=							IFWatermarker()

             return {
                 "text_encoder": text_encoder,
                 "tokenizer": tokenizer,
                 "unet": unet,
                 "scheduler": scheduler,
                 "watermarker": watermarker,
                 "safety_checker": None,
                 "feature_extractor": None,
             }



       def 					lowercase__    (							self      :  Union[str, Any]   )			->						List[str]:


             '''simple docstring'''




             torch.manual_seed(0   )
             UpperCAmelCase_      			=							TaEncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5"   )

             torch.manual_seed(0   )
             UpperCAmelCase_      			=							AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5"   )

             torch.manual_seed(0   )
             UpperCAmelCase_      			=							UNetaDConditionModel(
                 sample_size=32		,    layers_per_block=[1, 2]		,    block_out_channels=[32, 64]		,    down_block_types=[
                     "ResnetDownsampleBlock2D",
                     "SimpleCrossAttnDownBlock2D",
                 ]		,    mid_block_type="UNetMidBlock2DSimpleCrossAttn"		,    up_block_types=["SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"]		,    in_channels=6		,    out_channels=6		,    cross_attention_dim=32		,    encoder_hid_dim=32		,    attention_head_dim=8		,    addition_embed_type="text"		,    addition_embed_type_num_heads=2		,    cross_attention_norm="group_norm"		,    resnet_time_scale_shift="scale_shift"		,    act_fn="gelu"		,    class_embed_type="timestep"		,    mid_block_scale_factor=1.414		,    time_embedding_act_fn="gelu"		,    time_embedding_dim=32		,    )
             unet.set_attn_processor(AttnAddedKVProcessor()   )  # For reproducibility tests

             torch.manual_seed(0   )
             UpperCAmelCase_      			=							DDPMScheduler(
                 num_train_timesteps=1000		,    beta_schedule="squaredcos_cap_v2"		,    beta_start=0.0001		,    beta_end=0.02		,    thresholding=_UpperCAmelCase		,    dynamic_thresholding_ratio=0.95		,    sample_max_value=1.0		,    prediction_type="epsilon"		,    variance_type="learned_range"		,    )

             torch.manual_seed(0   )
             UpperCAmelCase_      			=							DDPMScheduler(
                 num_train_timesteps=1000		,    beta_schedule="squaredcos_cap_v2"		,    beta_start=0.0001		,    beta_end=0.02		,    )

             torch.manual_seed(0   )
             UpperCAmelCase_      			=							IFWatermarker()

             return {
                 "text_encoder": text_encoder,
                 "tokenizer": tokenizer,
                 "unet": unet,
                 "scheduler": scheduler,
                 "image_noising_scheduler": image_noising_scheduler,
                 "watermarker": watermarker,
                 "safety_checker": None,
                 "feature_extractor": None,
             }



       def 					lowercase__    (							self      :  List[Any]   )			->						List[Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.get_dummy_components()
             UpperCAmelCase_      			=							self.pipeline_class(**_UpperCAmelCase   )
             pipe.to(_UpperCAmelCase   )
             pipe.set_progress_bar_config(disable=_UpperCAmelCase   )

             UpperCAmelCase_      			=							self.get_dummy_inputs(_UpperCAmelCase   )

             UpperCAmelCase_      			=							inputs['prompt']
             UpperCAmelCase_      			=							inputs['generator']
             UpperCAmelCase_      			=							inputs['num_inference_steps']
             UpperCAmelCase_      			=							inputs['output_type']

             if "image" in inputs:
                   UpperCAmelCase_      			=							inputs['image']
             else:
                   UpperCAmelCase_      			=							None

             if "mask_image" in inputs:
                   UpperCAmelCase_      			=							inputs['mask_image']
             else:
                   UpperCAmelCase_      			=							None

             if "original_image" in inputs:
                   UpperCAmelCase_      			=							inputs['original_image']
             else:
                   UpperCAmelCase_      			=							None

             UpperCAmelCase_      			=							pipe.encode_prompt(_UpperCAmelCase   )

             # inputs with prompt converted to embeddings
             UpperCAmelCase_      			=							{
                 'prompt_embeds': prompt_embeds,
                 'negative_prompt_embeds': negative_prompt_embeds,
                 'generator': generator,
                 'num_inference_steps': num_inference_steps,
                 'output_type': output_type,
             }

             if image is not None:
                   UpperCAmelCase_      			=							image

             if mask_image is not None:
                   UpperCAmelCase_      			=							mask_image

             if original_image is not None:
                   UpperCAmelCase_      			=							original_image

             # set all optional components to None
             for optional_component in pipe._optional_components:
                   setattr(_UpperCAmelCase		,    _UpperCAmelCase		,    _UpperCAmelCase   )

             UpperCAmelCase_      			=							pipe(**_UpperCAmelCase   )[0]

             with tempfile.TemporaryDirectory() as tmpdir:
                   pipe.save_pretrained(_UpperCAmelCase   )
                   UpperCAmelCase_      			=							self.pipeline_class.from_pretrained(_UpperCAmelCase   )
                   pipe_loaded.to(_UpperCAmelCase   )
                   pipe_loaded.set_progress_bar_config(disable=_UpperCAmelCase   )

             pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor()   )  # For reproducibility tests

             for optional_component in pipe._optional_components:
                   self.assertTrue(
                       getattr(_UpperCAmelCase		,    _UpperCAmelCase   ) is None		,    F"""`{optional_component}` did not stay set to None after loading."""		,    )

             UpperCAmelCase_      			=							self.get_dummy_inputs(_UpperCAmelCase   )

             UpperCAmelCase_      			=							inputs['generator']
             UpperCAmelCase_      			=							inputs['num_inference_steps']
             UpperCAmelCase_      			=							inputs['output_type']

             # inputs with prompt converted to embeddings
             UpperCAmelCase_      			=							{
                 'prompt_embeds': prompt_embeds,
                 'negative_prompt_embeds': negative_prompt_embeds,
                 'generator': generator,
                 'num_inference_steps': num_inference_steps,
                 'output_type': output_type,
             }

             if image is not None:
                   UpperCAmelCase_      			=							image

             if mask_image is not None:
                   UpperCAmelCase_      			=							mask_image

             if original_image is not None:
                   UpperCAmelCase_      			=							original_image

             UpperCAmelCase_      			=							pipe_loaded(**_UpperCAmelCase   )[0]

             UpperCAmelCase_      			=							np.abs(to_np(_UpperCAmelCase   ) - to_np(_UpperCAmelCase   )   ).max()
             self.assertLess(_UpperCAmelCase		,    1e-4   )







       def 					lowercase__    (							self      :  Optional[Any]   )			->						Union[str, Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.get_dummy_components()
             UpperCAmelCase_      			=							self.pipeline_class(**_UpperCAmelCase   )
             pipe.to(_UpperCAmelCase   )
             pipe.set_progress_bar_config(disable=_UpperCAmelCase   )

             UpperCAmelCase_      			=							self.get_dummy_inputs(_UpperCAmelCase   )
             UpperCAmelCase_      			=							pipe(**_UpperCAmelCase   )[0]

             with tempfile.TemporaryDirectory() as tmpdir:
                   pipe.save_pretrained(_UpperCAmelCase   )
                   UpperCAmelCase_      			=							self.pipeline_class.from_pretrained(_UpperCAmelCase   )
                   pipe_loaded.to(_UpperCAmelCase   )
                   pipe_loaded.set_progress_bar_config(disable=_UpperCAmelCase   )

             pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor()   )  # For reproducibility tests

             UpperCAmelCase_      			=							self.get_dummy_inputs(_UpperCAmelCase   )
             UpperCAmelCase_      			=							pipe_loaded(**_UpperCAmelCase   )[0]

             UpperCAmelCase_      			=							np.abs(to_np(_UpperCAmelCase   ) - to_np(_UpperCAmelCase   )   ).max()
             self.assertLess(_UpperCAmelCase		,    1e-4   )









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


lowerCamelCase       	=						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)

lowerCamelCase       	=						{"""base""": """patrickvonplaten/wav2vec2_tiny_random""", """robust""": """patrickvonplaten/wav2vec2_tiny_random_robust"""}

lowerCamelCase       	=						"""zero2"""
lowerCamelCase       	=						"""zero3"""
lowerCamelCase       	=						[ZEROa, ZEROa]
def        a__     (				lowerCAmelCase__     ,      lowerCAmelCase__     ,      lowerCAmelCase__				):
      # 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
      UpperCAmelCase_      			=							parameterized.to_safe_name("_".join(str(lowerCAmelCase__				) for x in param.args				)				)
      return f"""{func.__name__}_{param_based_name}"""


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


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







       '''simple docstring'''


       @parameterized.expand(_UpperCAmelCase		,    name_func=_UpperCAmelCase   )
       def 					lowercase__    (							self      :  Dict		,    _UpperCAmelCase      :  int		,    _UpperCAmelCase      :  Any   )			->						Optional[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 					lowercase__    (							self      :  Any		,    _UpperCAmelCase      :  Optional[Any]		,    _UpperCAmelCase      :  str   )			->						Any:


             '''simple docstring'''




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



       @parameterized.expand(_UpperCAmelCase		,    name_func=_UpperCAmelCase   )
       def 					lowercase__    (							self      :  Optional[int]		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  List[str]   )			->						Union[str, 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 					lowercase__    (							self      :  int		,    _UpperCAmelCase      :  int		,    _UpperCAmelCase      :  Optional[int]   )			->						Optional[int]:


             '''simple docstring'''




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



       def 					lowercase__    (							self      :  Optional[Any]		,    _UpperCAmelCase      :  Tuple   )			->						Optional[int]:


             '''simple docstring'''




             pass



       def 					lowercase__    (							self      :  Optional[Any]		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  int = 10		,    _UpperCAmelCase      :  bool = True		,    _UpperCAmelCase      :  bool = True		,    _UpperCAmelCase      :  bool = True		,    )			->						Optional[Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							models[model]

             UpperCAmelCase_      			=							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 					lowercase__    (							self      :  Union[str, Any]		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  int = 10		,    _UpperCAmelCase      :  int = 1		,    _UpperCAmelCase      :  bool = True		,    _UpperCAmelCase      :  bool = True		,    )			->						Tuple:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.get_auto_remove_tmp_dir("./xxx"		,    after=_UpperCAmelCase   )
             UpperCAmelCase_      			=							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
             UpperCAmelCase_      			=							F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split()
             UpperCAmelCase_      			=							[F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""]
             UpperCAmelCase_      			=							self.get_launcher(_UpperCAmelCase   )

             UpperCAmelCase_      			=							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 					lowercase__    (							self      :  List[Any]		,    _UpperCAmelCase      :  int=False   )			->						Optional[Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							min(2		,    get_gpu_count()   ) if distributed else 1
             return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()




