






import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()




class 			snake_case__   (							unittest.TestCase):

       '''simple docstring'''



       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





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



       @property
       def 					__lowercase						(							self    ) ->      List[Any]:






            '''simple docstring'''





            __snake_case			:List[Any]          =						1
            __snake_case			:List[str]          =						3
            __snake_case			:List[Any]          =						(32, 32)

            __snake_case			:Optional[Any]          =						floats_tensor((batch_size, num_channels) + sizes			,						rng=random.Random(0    )    ).to(a__    )
            return image



       @property
       def 					__lowercase						(							self    ) ->      int:






            '''simple docstring'''





            torch.manual_seed(0    )
            __snake_case			:int          =						UNetaDConditionModel(
                block_out_channels=(32, 64)			,						layers_per_block=2			,						sample_size=32			,						in_channels=4			,						out_channels=4			,						down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")			,						up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")			,						cross_attention_dim=32			,						)
            return model



       @property
       def 					__lowercase						(							self    ) ->      Union[str, Any]:






            '''simple docstring'''





            torch.manual_seed(0    )
            __snake_case			:int          =						AutoencoderKL(
                block_out_channels=[32, 64]			,						in_channels=3			,						out_channels=3			,						down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]			,						up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]			,						latent_channels=4			,						)
            return model



       @property
       def 					__lowercase						(							self    ) ->      List[str]:






            '''simple docstring'''





            torch.manual_seed(0    )
            __snake_case			:Optional[int]          =						RobertaSeriesConfig(
                hidden_size=32			,						project_dim=32			,						intermediate_size=37			,						layer_norm_eps=1e-05			,						num_attention_heads=4			,						num_hidden_layers=5			,						pad_token_id=1			,						vocab_size=50_06			,						)
            return RobertaSeriesModelWithTransformation(a__    )



       @property
       def 					__lowercase						(							self    ) ->      List[str]:






            '''simple docstring'''





            def extract(*a__			,						**a__    ):




                 class 			snake_case__   :

                        '''simple docstring'''



                        def __init__(							self    ) ->      Optional[Any]:






                             '''simple docstring'''





                             __snake_case			:str          =						torch.ones([0]    )



                        def 					__lowercase						(							self			,						a__    ) ->      Union[str, Any]:






                             '''simple docstring'''





                             self.pixel_values.to(a__    )
                             return self
                 return Out()

            return extract



       def 					__lowercase						(							self    ) ->      str:






            '''simple docstring'''





            __snake_case			:Dict          =						"""cpu"""  # ensure determinism for the device-dependent torch.Generator
            __snake_case			:Optional[int]          =						self.dummy_cond_unet
            __snake_case			:Tuple          =						PNDMScheduler(skip_prk_steps=a__    )
            __snake_case			:Any          =						self.dummy_vae
            __snake_case			:Tuple          =						self.dummy_text_encoder
            __snake_case			:Dict          =						XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""    )
            __snake_case			:Optional[Any]          =						77

            __snake_case			:Any          =						self.dummy_image.to(a__    )
            __snake_case			:List[str]          =						init_image / 2 + 0.5

            # make sure here that pndm scheduler skips prk
            __snake_case			:Optional[int]          =						AltDiffusionImgaImgPipeline(
                unet=a__			,						scheduler=a__			,						vae=a__			,						text_encoder=a__			,						tokenizer=a__			,						safety_checker=a__			,						feature_extractor=self.dummy_extractor			,						)
            __snake_case			:int          =						VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor			,						do_normalize=a__    )
            __snake_case			:str          =						alt_pipe.to(a__    )
            alt_pipe.set_progress_bar_config(disable=a__    )

            __snake_case			:Tuple          =						"""A painting of a squirrel eating a burger"""
            __snake_case			:Union[str, Any]          =						torch.Generator(device=a__    ).manual_seed(0    )
            __snake_case			:int          =						alt_pipe(
                [prompt]			,						generator=a__			,						guidance_scale=6.0			,						num_inference_steps=2			,						output_type="""np"""			,						image=a__			,						)

            __snake_case			:Dict          =						output.images

            __snake_case			:Optional[int]          =						torch.Generator(device=a__    ).manual_seed(0    )
            __snake_case			:List[str]          =						alt_pipe(
                [prompt]			,						generator=a__			,						guidance_scale=6.0			,						num_inference_steps=2			,						output_type="""np"""			,						image=a__			,						return_dict=a__			,						)[0]

            __snake_case			:Optional[int]          =						image[0, -3:, -3:, -1]
            __snake_case			:Any          =						image_from_tuple[0, -3:, -3:, -1]

            assert image.shape == (1, 32, 32, 3)
            __snake_case			:Tuple          =						np.array([0.44_27, 0.37_31, 0.42_49, 0.49_41, 0.45_46, 0.41_48, 0.41_93, 0.46_66, 0.44_99]    )

            assert np.abs(image_slice.flatten() - expected_slice    ).max() < 5e-3
            assert np.abs(image_from_tuple_slice.flatten() - expected_slice    ).max() < 5e-3



       @unittest.skipIf(torch_device != """cuda"""			,						"""This test requires a GPU"""    )
       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





            __snake_case			:Any          =						self.dummy_cond_unet
            __snake_case			:Optional[int]          =						PNDMScheduler(skip_prk_steps=a__    )
            __snake_case			:int          =						self.dummy_vae
            __snake_case			:Tuple          =						self.dummy_text_encoder
            __snake_case			:List[str]          =						XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""    )
            __snake_case			:Optional[int]          =						77

            __snake_case			:Optional[int]          =						self.dummy_image.to(a__    )

            # put models in fp16
            __snake_case			:Optional[int]          =						unet.half()
            __snake_case			:Optional[int]          =						vae.half()
            __snake_case			:Optional[Any]          =						bert.half()

            # make sure here that pndm scheduler skips prk
            __snake_case			:List[Any]          =						AltDiffusionImgaImgPipeline(
                unet=a__			,						scheduler=a__			,						vae=a__			,						text_encoder=a__			,						tokenizer=a__			,						safety_checker=a__			,						feature_extractor=self.dummy_extractor			,						)
            __snake_case			:Optional[int]          =						VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor			,						do_normalize=a__    )
            __snake_case			:List[str]          =						alt_pipe.to(a__    )
            alt_pipe.set_progress_bar_config(disable=a__    )

            __snake_case			:Optional[Any]          =						"""A painting of a squirrel eating a burger"""
            __snake_case			:Tuple          =						torch.manual_seed(0    )
            __snake_case			:List[str]          =						alt_pipe(
                [prompt]			,						generator=a__			,						num_inference_steps=2			,						output_type="""np"""			,						image=a__			,						).images

            assert image.shape == (1, 32, 32, 3)



       @unittest.skipIf(torch_device != """cuda"""			,						"""This test requires a GPU"""    )
       def 					__lowercase						(							self    ) ->      Optional[Any]:






            '''simple docstring'''





            __snake_case			:Tuple          =						load_image(
                """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
                """/img2img/sketch-mountains-input.jpg"""    )
            # resize to resolution that is divisible by 8 but not 16 or 32
            __snake_case			:List[str]          =						init_image.resize((7_60, 5_04)    )

            __snake_case			:str          =						"""BAAI/AltDiffusion"""
            __snake_case			:str          =						AltDiffusionImgaImgPipeline.from_pretrained(
                a__			,						safety_checker=a__			,						)
            pipe.to(a__    )
            pipe.set_progress_bar_config(disable=a__    )
            pipe.enable_attention_slicing()

            __snake_case			:List[str]          =						"""A fantasy landscape, trending on artstation"""

            __snake_case			:Dict          =						torch.manual_seed(0    )
            __snake_case			:str          =						pipe(
                prompt=a__			,						image=a__			,						strength=0.75			,						guidance_scale=7.5			,						generator=a__			,						output_type="""np"""			,						)
            __snake_case			:Optional[int]          =						output.images[0]

            __snake_case			:Union[str, Any]          =						image[2_55:2_58, 3_83:3_86, -1]

            assert image.shape == (5_04, 7_60, 3)
            __snake_case			:Dict          =						np.array([0.93_58, 0.93_97, 0.95_99, 0.99_01, 1.00_00, 1.00_00, 0.98_82, 1.00_00, 1.00_00]    )

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




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

       '''simple docstring'''



       def 					__lowercase						(							self    ) ->      Any:






            '''simple docstring'''





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



       def 					__lowercase						(							self    ) ->      Any:






            '''simple docstring'''





            __snake_case			:Dict          =						load_image(
                """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
                """/img2img/sketch-mountains-input.jpg"""    )
            __snake_case			:Optional[Any]          =						init_image.resize((7_68, 5_12)    )
            __snake_case			:str          =						load_numpy(
                """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"""    )

            __snake_case			:Any          =						"""BAAI/AltDiffusion"""
            __snake_case			:Optional[int]          =						AltDiffusionImgaImgPipeline.from_pretrained(
                a__			,						safety_checker=a__			,						)
            pipe.to(a__    )
            pipe.set_progress_bar_config(disable=a__    )
            pipe.enable_attention_slicing()

            __snake_case			:Dict          =						"""A fantasy landscape, trending on artstation"""

            __snake_case			:Optional[int]          =						torch.manual_seed(0    )
            __snake_case			:List[str]          =						pipe(
                prompt=a__			,						image=a__			,						strength=0.75			,						guidance_scale=7.5			,						generator=a__			,						output_type="""np"""			,						)
            __snake_case			:Optional[Any]          =						output.images[0]

            assert image.shape == (5_12, 7_68, 3)
            # img2img is flaky across GPUs even in fp32, so using MAE here
            assert np.abs(expected_image - image    ).max() < 1e-2










import importlib
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
import transformers.models.auto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.bert.configuration_bert import BertConfig
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils"""))

from test_module.custom_configuration import CustomConfig  # noqa E402


lowerCamelCase__							=     get_tests_dir("""fixtures/dummy-config.json""")




class 			snake_case__   (							unittest.TestCase):

       '''simple docstring'''



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






            '''simple docstring'''





            __snake_case			:Optional[int]          =						0



       def 					__lowercase						(							self    ) ->      int:






            '''simple docstring'''





            self.assertIsNotNone(transformers.models.auto.__spec__    )
            self.assertIsNotNone(importlib.util.find_spec("""transformers.models.auto"""    )    )



       def 					__lowercase						(							self    ) ->      List[str]:






            '''simple docstring'''





            __snake_case			:Optional[Any]          =						AutoConfig.from_pretrained("""bert-base-uncased"""    )
            self.assertIsInstance(a__			,						a__    )



       def 					__lowercase						(							self    ) ->      Optional[int]:






            '''simple docstring'''





            __snake_case			:List[str]          =						AutoConfig.from_pretrained(a__    )
            self.assertIsInstance(a__			,						a__    )



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






            '''simple docstring'''





            __snake_case			:Tuple          =						AutoConfig.from_pretrained(a__    )
            self.assertIsInstance(a__			,						a__    )



       def 					__lowercase						(							self    ) ->      str:






            '''simple docstring'''





            __snake_case			:Optional[int]          =						AutoConfig.for_model("""roberta"""    )
            self.assertIsInstance(a__			,						a__    )



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






            '''simple docstring'''





            with tempfile.TemporaryDirectory() as tmp_dir:
                 # This model name contains bert and roberta, but roberta ends up being picked.
                 __snake_case			:List[Any]          =						os.path.join(a__			,						"""fake-roberta"""    )
                 os.makedirs(a__			,						exist_ok=a__    )
                 with open(os.path.join(a__			,						"""config.json"""    )			,						"""w"""    ) as f:
                      f.write(json.dumps({}    )    )
                 __snake_case			:Optional[Any]          =						AutoConfig.from_pretrained(a__    )
                 self.assertEqual(type(a__    )			,						a__    )



       def 					__lowercase						(							self    ) ->      Dict:






            '''simple docstring'''





            try:
                 AutoConfig.register("""custom"""			,						a__    )
                 # Wrong model type will raise an error
                 with self.assertRaises(a__    ):
                      AutoConfig.register("""model"""			,						a__    )
                 # Trying to register something existing in the Transformers library will raise an error
                 with self.assertRaises(a__    ):
                      AutoConfig.register("""bert"""			,						a__    )

                 # Now that the config is registered, it can be used as any other config with the auto-API
                 __snake_case			:Optional[int]          =						CustomConfig()
                 with tempfile.TemporaryDirectory() as tmp_dir:
                      config.save_pretrained(a__    )
                      __snake_case			:Tuple          =						AutoConfig.from_pretrained(a__    )
                      self.assertIsInstance(a__			,						a__    )

            finally:
                 if "custom" in CONFIG_MAPPING._extra_content:
                      del CONFIG_MAPPING._extra_content["custom"]



       def 					__lowercase						(							self    ) ->      int:






            '''simple docstring'''





            with self.assertRaisesRegex(
                a__			,						"""bert-base is not a local folder and is not a valid model identifier"""    ):
                 __snake_case			:str          =						AutoConfig.from_pretrained("""bert-base"""    )



       def 					__lowercase						(							self    ) ->      str:






            '''simple docstring'''





            with self.assertRaisesRegex(
                a__			,						R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""    ):
                 __snake_case			:Dict          =						AutoConfig.from_pretrained(a__			,						revision="""aaaaaa"""    )



       def 					__lowercase						(							self    ) ->      Optional[Any]:






            '''simple docstring'''





            with self.assertRaisesRegex(
                a__			,						"""hf-internal-testing/no-config-test-repo does not appear to have a file named config.json."""			,						):
                 __snake_case			:Optional[int]          =						AutoConfig.from_pretrained("""hf-internal-testing/no-config-test-repo"""    )



       def 					__lowercase						(							self    ) ->      int:






            '''simple docstring'''





            with self.assertRaises(a__    ):
                 __snake_case			:Dict          =						AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""    )
            # If remote code is disabled, we can't load this config.
            with self.assertRaises(a__    ):
                 __snake_case			:int          =						AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""			,						trust_remote_code=a__    )

            __snake_case			:Tuple          =						AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""			,						trust_remote_code=a__    )
            self.assertEqual(config.__class__.__name__			,						"""NewModelConfig"""    )

            # Test config can be reloaded.
            with tempfile.TemporaryDirectory() as tmp_dir:
                 config.save_pretrained(a__    )
                 __snake_case			:Union[str, Any]          =						AutoConfig.from_pretrained(a__			,						trust_remote_code=a__    )
            self.assertEqual(reloaded_config.__class__.__name__			,						"""NewModelConfig"""    )



       def 					__lowercase						(							self    ) ->      Dict:






            '''simple docstring'''





            class 			snake_case__   (							lowercase_):

                   '''simple docstring'''
                   lowerCamelCase							:				Optional[Any] 				= "new-model"

            try:
                 AutoConfig.register("""new-model"""			,						a__    )
                 # If remote code is not set, the default is to use local
                 __snake_case			:List[Any]          =						AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""    )
                 self.assertEqual(config.__class__.__name__			,						"""NewModelConfigLocal"""    )

                 # If remote code is disabled, we load the local one.
                 __snake_case			:Tuple          =						AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""			,						trust_remote_code=a__    )
                 self.assertEqual(config.__class__.__name__			,						"""NewModelConfigLocal"""    )

                 # If remote is enabled, we load from the Hub
                 __snake_case			:List[Any]          =						AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""			,						trust_remote_code=a__    )
                 self.assertEqual(config.__class__.__name__			,						"""NewModelConfig"""    )

            finally:
                 if "new-model" in CONFIG_MAPPING._extra_content:
                      del CONFIG_MAPPING._extra_content["new-model"]


