


from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


SCREAMING_SNAKE_CASE__					:     Optional[int]       =     logging.get_logger(__name__)

SCREAMING_SNAKE_CASE__					:     Optional[int]       =     {
    'xlm-mlm-en-2048': 'https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json',
    'xlm-mlm-ende-1024': 'https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json',
    'xlm-mlm-enfr-1024': 'https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json',
    'xlm-mlm-enro-1024': 'https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json',
    'xlm-mlm-tlm-xnli15-1024': 'https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json',
    'xlm-mlm-xnli15-1024': 'https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json',
    'xlm-clm-enfr-1024': 'https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json',
    'xlm-clm-ende-1024': 'https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json',
    'xlm-mlm-17-1280': 'https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json',
    'xlm-mlm-100-1280': 'https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json',
}


class 		_SCREAMING_SNAKE_CASE     (						A     ):
     __SCREAMING_SNAKE_CASE     					=    '''xlm'''
     __SCREAMING_SNAKE_CASE     					=    {
         '''hidden_size''': '''emb_dim''',
         '''num_attention_heads''': '''n_heads''',
         '''num_hidden_layers''': '''n_layers''',
         '''n_words''': '''vocab_size''',  # For backward compatibility
     }


     def __init__(  self							,					A_=3_01_45							,					A_=20_48							,					A_=12							,					A_=16							,					A_=0.1							,					A_=0.1							,					A_=True							,					A_=False							,					A_=False							,					A_=False							,					A_=1							,					A_=True							,					A_=5_12							,					A_=20_48**-0.5							,					A_=1e-12							,					A_=0.0_2							,					A_=0							,					A_=1							,					A_=2							,					A_=3							,					A_=5							,					A_=True							,					A_="first"							,					A_=True							,					A_=None							,					A_=True							,					A_=0.1							,					A_=5							,					A_=5							,					A_=0							,					A_=0							,					A_=2							,					A_=0							,					**A_							,					):
       _UpperCAmelCase		:							Tuple							=     vocab_size
       _UpperCAmelCase		:							List[str]							=     emb_dim
       _UpperCAmelCase		:							str							=     n_layers
       _UpperCAmelCase		:							int							=     n_heads
       _UpperCAmelCase		:							Optional[int]							=     dropout
       _UpperCAmelCase		:							Any							=     attention_dropout
       _UpperCAmelCase		:							str							=     gelu_activation
       _UpperCAmelCase		:							str							=     sinusoidal_embeddings
       _UpperCAmelCase		:							Union[str, Any]							=     causal
       _UpperCAmelCase		:							Optional[int]							=     asm
       _UpperCAmelCase		:							Union[str, Any]							=     n_langs
       _UpperCAmelCase		:							List[Any]							=     use_lang_emb
       _UpperCAmelCase		:							List[str]							=     layer_norm_eps
       _UpperCAmelCase		:							Optional[Any]							=     bos_index
       _UpperCAmelCase		:							List[Any]							=     eos_index
       _UpperCAmelCase		:							Optional[Any]							=     pad_index
       _UpperCAmelCase		:							str							=     unk_index
       _UpperCAmelCase		:							Dict							=     mask_index
       _UpperCAmelCase		:							Union[str, Any]							=     is_encoder
       _UpperCAmelCase		:							Optional[Any]							=     max_position_embeddings
       _UpperCAmelCase		:							int							=     embed_init_std
       _UpperCAmelCase		:							str							=     init_std
       _UpperCAmelCase		:							str							=     summary_type
       _UpperCAmelCase		:							Tuple							=     summary_use_proj
       _UpperCAmelCase		:							Optional[Any]							=     summary_activation
       _UpperCAmelCase		:							Optional[Any]							=     summary_proj_to_labels
       _UpperCAmelCase		:							str							=     summary_first_dropout
       _UpperCAmelCase		:							Optional[Any]							=     start_n_top
       _UpperCAmelCase		:							List[Any]							=     end_n_top
       _UpperCAmelCase		:							Dict							=     mask_token_id
       _UpperCAmelCase		:							int							=     lang_id

       if "n_words" in kwargs:
         _UpperCAmelCase		:							Dict							=     kwargs["""n_words"""]

       super().__init__(pad_token_id=A_							,					bos_token_id=A_							,					**A_    )


class 		_SCREAMING_SNAKE_CASE     (						A     ):


     @property
     def        __snake_case(  self    ):
       if self.task == "multiple-choice":
         _UpperCAmelCase		:							int							=     {0: """batch""", 1: """choice""", 2: """sequence"""}
       else:
         _UpperCAmelCase		:							Dict							=     {0: """batch""", 1: """sequence"""}
       return OrderedDict(
           [
               ("""input_ids""", dynamic_axis),
               ("""attention_mask""", dynamic_axis),
               ("""token_type_ids""", dynamic_axis),
           ]    )









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 		_SCREAMING_SNAKE_CASE     (						A							,	A							,	unittest.TestCase     ):
     __SCREAMING_SNAKE_CASE     					=    IFPipeline
     __SCREAMING_SNAKE_CASE     					=    TEXT_TO_IMAGE_PARAMS - {'''width''', '''height''', '''latents'''}
     __SCREAMING_SNAKE_CASE     					=    TEXT_TO_IMAGE_BATCH_PARAMS
     __SCREAMING_SNAKE_CASE     					=    PipelineTesterMixin.required_optional_params - {'''latents'''}


     def        __snake_case(  self    ):
       return self._get_dummy_components()


     def        __snake_case(  self							,					A_							,					A_=0    ):
       if str(A_    ).startswith("""mps"""    ):
         _UpperCAmelCase		:							Tuple							=     torch.manual_seed(A_    )
       else:
         _UpperCAmelCase		:							Optional[Any]							=     torch.Generator(device=A_    ).manual_seed(A_    )

       _UpperCAmelCase		:							Any							=     {
           """prompt""": """A painting of a squirrel eating a burger""",
           """generator""": generator,
           """num_inference_steps""": 2,
           """output_type""": """numpy""",
       }

       return inputs


     def        __snake_case(  self    ):
       self._test_save_load_optional_components()


     @unittest.skipIf(torch_device != """cuda"""							,					reason="""float16 requires CUDA"""    )
     def        __snake_case(  self    ):
       # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
       super().test_save_load_floataa(expected_max_diff=1e-1    )


     def        __snake_case(  self    ):
       self._test_attention_slicing_forward_pass(expected_max_diff=1e-2    )


     def        __snake_case(  self    ):
       self._test_save_load_local()


     def        __snake_case(  self    ):
       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        __snake_case(  self    ):
       self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3    )


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


     def        __snake_case(  self    ):
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()


     def        __snake_case(  self    ):
       # if

       _UpperCAmelCase		:							List[str]							=     IFPipeline.from_pretrained("""DeepFloyd/IF-I-XL-v1.0"""							,					variant="""fp16"""							,					torch_dtype=torch.floataa    )

       _UpperCAmelCase		:							Dict							=     IFSuperResolutionPipeline.from_pretrained(
           """DeepFloyd/IF-II-L-v1.0"""							,					variant="""fp16"""							,					torch_dtype=torch.floataa							,					text_encoder=A_							,					tokenizer=A_    )

       # pre compute text embeddings and remove T5 to save memory

       pipe_a.text_encoder.to("""cuda"""    )

       _UpperCAmelCase,_UpperCAmelCase		:							Dict							=     pipe_a.encode_prompt("""anime turtle"""							,					device="""cuda"""    )

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

       _UpperCAmelCase		:							List[Any]							=     None
       _UpperCAmelCase		:							Any							=     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(A_							,					A_							,					A_							,					A_    )

       pipe_a.remove_all_hooks()
       pipe_a.remove_all_hooks()

       # img2img

       _UpperCAmelCase		:							Any							=     IFImgaImgPipeline(**pipe_a.components    )
       _UpperCAmelCase		:							Union[str, Any]							=     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(A_							,					A_							,					A_							,					A_    )

       pipe_a.remove_all_hooks()
       pipe_a.remove_all_hooks()

       # inpainting

       _UpperCAmelCase		:							Optional[int]							=     IFInpaintingPipeline(**pipe_a.components    )
       _UpperCAmelCase		:							Union[str, Any]							=     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(A_							,					A_							,					A_							,					A_    )


     def        __snake_case(  self							,					A_							,					A_							,					A_							,					A_    ):
       # pipeline 1

       _start_torch_memory_measurement()

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

       _UpperCAmelCase		:							int							=     output.images[0]

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

       _UpperCAmelCase		:							Dict							=     torch.cuda.max_memory_allocated()
       assert mem_bytes < 13 * 10**9

       _UpperCAmelCase		:							str							=     load_numpy(
           """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy"""    )
       assert_mean_pixel_difference(A_							,					A_    )

       # pipeline 2

       _start_torch_memory_measurement()

       _UpperCAmelCase		:							List[Any]							=     torch.Generator(device="""cpu"""    ).manual_seed(0    )

       _UpperCAmelCase		:							str							=     floats_tensor((1, 3, 64, 64)							,					rng=random.Random(0    )    ).to(A_    )

       _UpperCAmelCase		:							str							=     pipe_a(
           prompt_embeds=A_							,					negative_prompt_embeds=A_							,					image=A_							,					generator=A_							,					num_inference_steps=2							,					output_type="""np"""							,					)

       _UpperCAmelCase		:							int							=     output.images[0]

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

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

       _UpperCAmelCase		:							List[Any]							=     load_numpy(
           """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy"""    )
       assert_mean_pixel_difference(A_							,					A_    )


     def        __snake_case(  self							,					A_							,					A_							,					A_							,					A_    ):
       # pipeline 1

       _start_torch_memory_measurement()

       _UpperCAmelCase		:							Optional[int]							=     floats_tensor((1, 3, 64, 64)							,					rng=random.Random(0    )    ).to(A_    )

       _UpperCAmelCase		:							Dict							=     torch.Generator(device="""cpu"""    ).manual_seed(0    )

       _UpperCAmelCase		:							List[str]							=     pipe_a(
           prompt_embeds=A_							,					negative_prompt_embeds=A_							,					image=A_							,					num_inference_steps=2							,					generator=A_							,					output_type="""np"""							,					)

       _UpperCAmelCase		:							int							=     output.images[0]

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

       _UpperCAmelCase		:							str							=     torch.cuda.max_memory_allocated()
       assert mem_bytes < 10 * 10**9

       _UpperCAmelCase		:							str							=     load_numpy(
           """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy"""    )
       assert_mean_pixel_difference(A_							,					A_    )

       # pipeline 2

       _start_torch_memory_measurement()

       _UpperCAmelCase		:							List[str]							=     torch.Generator(device="""cpu"""    ).manual_seed(0    )

       _UpperCAmelCase		:							Union[str, Any]							=     floats_tensor((1, 3, 2_56, 2_56)							,					rng=random.Random(0    )    ).to(A_    )
       _UpperCAmelCase		:							Optional[int]							=     floats_tensor((1, 3, 64, 64)							,					rng=random.Random(0    )    ).to(A_    )

       _UpperCAmelCase		:							Optional[int]							=     pipe_a(
           prompt_embeds=A_							,					negative_prompt_embeds=A_							,					image=A_							,					original_image=A_							,					generator=A_							,					num_inference_steps=2							,					output_type="""np"""							,					)

       _UpperCAmelCase		:							Dict							=     output.images[0]

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

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

       _UpperCAmelCase		:							int							=     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(A_							,					A_    )




     def        __snake_case(  self							,					A_							,					A_							,					A_							,					A_    ):
       # pipeline 1

       _start_torch_memory_measurement()

       _UpperCAmelCase		:							List[Any]							=     floats_tensor((1, 3, 64, 64)							,					rng=random.Random(0    )    ).to(A_    )
       _UpperCAmelCase		:							Dict							=     floats_tensor((1, 3, 64, 64)							,					rng=random.Random(1    )    ).to(A_    )

       _UpperCAmelCase		:							Optional[Any]							=     torch.Generator(device="""cpu"""    ).manual_seed(0    )
       _UpperCAmelCase		:							str							=     pipe_a(
           prompt_embeds=A_							,					negative_prompt_embeds=A_							,					image=A_							,					mask_image=A_							,					num_inference_steps=2							,					generator=A_							,					output_type="""np"""							,					)

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

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

       _UpperCAmelCase		:							List[str]							=     torch.cuda.max_memory_allocated()
       assert mem_bytes < 10 * 10**9

       _UpperCAmelCase		:							Dict							=     load_numpy(
           """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy"""    )
       assert_mean_pixel_difference(A_							,					A_    )

       # pipeline 2

       _start_torch_memory_measurement()

       _UpperCAmelCase		:							str							=     torch.Generator(device="""cpu"""    ).manual_seed(0    )

       _UpperCAmelCase		:							Optional[int]							=     floats_tensor((1, 3, 64, 64)							,					rng=random.Random(0    )    ).to(A_    )
       _UpperCAmelCase		:							Tuple							=     floats_tensor((1, 3, 2_56, 2_56)							,					rng=random.Random(0    )    ).to(A_    )
       _UpperCAmelCase		:							str							=     floats_tensor((1, 3, 2_56, 2_56)							,					rng=random.Random(1    )    ).to(A_    )

       _UpperCAmelCase		:							Union[str, Any]							=     pipe_a(
           prompt_embeds=A_							,					negative_prompt_embeds=A_							,					image=A_							,					mask_image=A_							,					original_image=A_							,					generator=A_							,					num_inference_steps=2							,					output_type="""np"""							,					)

       _UpperCAmelCase		:							Any							=     output.images[0]

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

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

       _UpperCAmelCase		:							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(A_							,					A_    )




def    a__    (		):
  torch.cuda.empty_cache()
  torch.cuda.reset_max_memory_allocated()
  torch.cuda.reset_peak_memory_stats()





