






import gc
import random
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()




class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					,  SCREAMING_SNAKE_CASE__					,  unittest.TestCase					):


						'''simple docstring'''




						A     :   Optional[Any]						=					StableDiffusionXLImgaImgPipeline
						A     :   str						=					TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width'}
						A     :   Union[str, Any]						=					PipelineTesterMixin.required_optional_params - {'latents'}
						A     :   List[Any]						=					TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
						A     :   Union[str, Any]						=					IMAGE_TO_IMAGE_IMAGE_PARAMS
						A     :   Any						=					IMAGE_TO_IMAGE_IMAGE_PARAMS






						def       _lowerCAmelCase       (	self				) ->				Optional[int]:
								torch.manual_seed(0				)
								snake_case_				:							Any						 =       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")		,				attention_head_dim=(2, 4)		,				use_linear_projection=_SCREAMING_SNAKE_CASE		,				addition_embed_type="text_time"		,				addition_time_embed_dim=8		,				transformer_layers_per_block=(1, 2)		,				projection_class_embeddings_input_dim=80		,				cross_attention_dim=64		,				)
								snake_case_				:							Optional[Any]						 =       EulerDiscreteScheduler(
								    beta_start=0.0_0085		,				beta_end=0.012		,				steps_offset=1		,				beta_schedule="scaled_linear"		,				timestep_spacing="leading"		,				)
								torch.manual_seed(0				)
								snake_case_				:							Any						 =       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		,				sample_size=128		,				)
								torch.manual_seed(0				)
								snake_case_				:							Optional[Any]						 =       CLIPTextConfig(
								    bos_token_id=0		,				eos_token_id=2		,				hidden_size=32		,				intermediate_size=37		,				layer_norm_eps=1e-05		,				num_attention_heads=4		,				num_hidden_layers=5		,				pad_token_id=1		,				vocab_size=1000		,				hidden_act="gelu"		,				projection_dim=32		,				)
								snake_case_				:							Tuple						 =       CLIPTextModel(_SCREAMING_SNAKE_CASE				)
								snake_case_				:							Optional[Any]						 =       CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"		,				local_files_only=_SCREAMING_SNAKE_CASE				)

								snake_case_				:							Optional[int]						 =       CLIPTextModelWithProjection(_SCREAMING_SNAKE_CASE				)
								snake_case_				:							Optional[Any]						 =       CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"		,				local_files_only=_SCREAMING_SNAKE_CASE				)

								snake_case_				:							int						 =       {
								    "unet": unet,
								    "scheduler": scheduler,
								    "vae": vae,
								    "text_encoder": text_encoder,
								    "tokenizer": tokenizer,
								    "text_encoder_2": text_encoder_a,
								    "tokenizer_2": tokenizer_a,
								    # "safety_checker": None,
								    # "feature_extractor": None,
								}
								return components






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE=0				) ->				Any:
								snake_case_				:							List[Any]						 =       floats_tensor((1, 3, 32, 32)		,				rng=random.Random(_SCREAMING_SNAKE_CASE				)				).to(_SCREAMING_SNAKE_CASE				)
								snake_case_				:							Optional[int]						 =       image / 2 + 0.5
								if str(_SCREAMING_SNAKE_CASE				).startswith("mps"				):
										snake_case_				:							Any						 =       torch.manual_seed(_SCREAMING_SNAKE_CASE				)
								else:
										snake_case_				:							Dict						 =       torch.Generator(device=_SCREAMING_SNAKE_CASE				).manual_seed(_SCREAMING_SNAKE_CASE				)
								snake_case_				:							Any						 =       {
								    "prompt": "A painting of a squirrel eating a burger",
								    "image": image,
								    "generator": generator,
								    "num_inference_steps": 2,
								    "guidance_scale": 5.0,
								    "output_type": "numpy",
								    "strength": 0.75,
								}
								return inputs






						def       _lowerCAmelCase       (	self				) ->				Union[str, Any]:
								snake_case_				:							List[Any]						 =       "cpu"  # ensure determinism for the device-dependent torch.Generator
								snake_case_				:							Any						 =       self.get_dummy_components()
								snake_case_				:							Any						 =       StableDiffusionXLImgaImgPipeline(**_SCREAMING_SNAKE_CASE				)
								snake_case_				:							Optional[Any]						 =       sd_pipe.to(_SCREAMING_SNAKE_CASE				)
								sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE				)

								snake_case_				:							List[Any]						 =       self.get_dummy_inputs(_SCREAMING_SNAKE_CASE				)
								snake_case_				:							Dict						 =       sd_pipe(**_SCREAMING_SNAKE_CASE				).images
								snake_case_				:							List[str]						 =       image[0, -3:, -3:, -1]

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

								snake_case_				:							List[Any]						 =       np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165]				)

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






						def       _lowerCAmelCase       (	self				) ->				int:
								super().test_attention_slicing_forward_pass(expected_max_diff=3e-3				)






						def       _lowerCAmelCase       (	self				) ->				Dict:
								super().test_inference_batch_single_identical(expected_max_diff=3e-3				)






						def       _lowerCAmelCase       (	self				) ->				int:
								pass






						def       _lowerCAmelCase       (	self				) ->				List[Any]:
								snake_case_				:							str						 =       self.get_dummy_components()
								snake_case_				:							Optional[Any]						 =       StableDiffusionXLImgaImgPipeline(**_SCREAMING_SNAKE_CASE				)
								snake_case_				:							Optional[int]						 =       sd_pipe.to(_SCREAMING_SNAKE_CASE				)
								snake_case_				:							Union[str, Any]						 =       sd_pipe.to(_SCREAMING_SNAKE_CASE				)
								sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE				)

								# forward without prompt embeds
								snake_case_				:							Optional[int]						 =       self.get_dummy_inputs(_SCREAMING_SNAKE_CASE				)
								snake_case_				:							List[Any]						 =       3 * ["this is a negative prompt"]
								snake_case_				:							Optional[int]						 =       negative_prompt
								snake_case_				:							List[Any]						 =       3 * [inputs["prompt"]]

								snake_case_				:							Optional[int]						 =       sd_pipe(**_SCREAMING_SNAKE_CASE				)
								snake_case_				:							str						 =       output.images[0, -3:, -3:, -1]

								# forward with prompt embeds
								snake_case_				:							Union[str, Any]						 =       self.get_dummy_inputs(_SCREAMING_SNAKE_CASE				)
								snake_case_				:							Tuple						 =       3 * ["this is a negative prompt"]
								snake_case_				:							Tuple						 =       3 * [inputs.pop("prompt"				)]

								(
								    (
								    snake_case_
								) ,       (
								    snake_case_
								) ,       (
								    snake_case_
								) ,       (
								    snake_case_
								) ,       
								)				:							Optional[Any]						 =       sd_pipe.encode_prompt(_SCREAMING_SNAKE_CASE		,				negative_prompt=_SCREAMING_SNAKE_CASE				)

								snake_case_				:							List[Any]						 =       sd_pipe(
								    **_SCREAMING_SNAKE_CASE		,				prompt_embeds=_SCREAMING_SNAKE_CASE		,				negative_prompt_embeds=_SCREAMING_SNAKE_CASE		,				pooled_prompt_embeds=_SCREAMING_SNAKE_CASE		,				negative_pooled_prompt_embeds=_SCREAMING_SNAKE_CASE		,				)
								snake_case_				:							int						 =       output.images[0, -3:, -3:, -1]

								# make sure that it's equal
								assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()				).max() < 1e-4




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


						'''simple docstring'''




						def       _lowerCAmelCase       (	self				) ->				int:
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE="cpu"		,				_SCREAMING_SNAKE_CASE=torch.floataa		,				_SCREAMING_SNAKE_CASE=0				) ->				Dict:
								snake_case_				:							List[str]						 =       torch.Generator(device=_SCREAMING_SNAKE_CASE				).manual_seed(_SCREAMING_SNAKE_CASE				)
								snake_case_				:							Dict						 =       np.random.RandomState(_SCREAMING_SNAKE_CASE				).standard_normal((1, 4, 64, 64)				)
								snake_case_				:							Tuple						 =       torch.from_numpy(_SCREAMING_SNAKE_CASE				).to(device=_SCREAMING_SNAKE_CASE		,				dtype=_SCREAMING_SNAKE_CASE				)
								snake_case_				:							Any						 =       {
								    "prompt": "a photograph of an astronaut riding a horse",
								    "latents": latents,
								    "generator": generator,
								    "num_inference_steps": 3,
								    "guidance_scale": 7.5,
								    "output_type": "numpy",
								}
								return inputs






						def       _lowerCAmelCase       (	self				) ->				List[str]:
								snake_case_				:							str						 =       DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base"				)
								pipe.to(_SCREAMING_SNAKE_CASE				)
								pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE				)

								snake_case_				:							int						 =       self.get_inputs(_SCREAMING_SNAKE_CASE				)
								snake_case_				:							Any						 =       pipe(**_SCREAMING_SNAKE_CASE				).images
								snake_case_				:							Optional[Any]						 =       image[0, -3:, -3:, -1].flatten()

								assert image.shape == (1, 512, 512, 3)
								snake_case_				:							int						 =       np.array([0.4_9493, 0.4_7896, 0.4_0798, 0.5_4214, 0.5_3212, 0.4_8202, 0.4_7656, 0.4_6329, 0.4_8506]				)
								assert np.abs(image_slice - expected_slice				).max() < 7e-3








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


lowercase  :							Optional[Any]			  =    get_tests_dir('''fixtures/dummy-config.json''')




class 		UpperCAmelCase_						(	unittest.TestCase					):


						'''simple docstring'''




						def       _lowerCAmelCase       (	self				) ->				int:
								snake_case_				:							str						 =       0






						def       _lowerCAmelCase       (	self				) ->				str:
								self.assertIsNotNone(transformers.models.auto.__spec__				)
								self.assertIsNotNone(importlib.util.find_spec("transformers.models.auto"				)				)






						def       _lowerCAmelCase       (	self				) ->				int:
								snake_case_				:							List[Any]						 =       AutoConfig.from_pretrained("bert-base-uncased"				)
								self.assertIsInstance(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self				) ->				Optional[int]:
								snake_case_				:							List[str]						 =       AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE				)
								self.assertIsInstance(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self				) ->				str:
								snake_case_				:							str						 =       AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE				)
								self.assertIsInstance(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self				) ->				Dict:
								snake_case_				:							Tuple						 =       AutoConfig.for_model("roberta"				)
								self.assertIsInstance(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self				) ->				Tuple:
								with tempfile.TemporaryDirectory() as tmp_dir:
										# This model name contains bert and roberta, but roberta ends up being picked.
										snake_case_				:							str						 =       os.path.join(_SCREAMING_SNAKE_CASE		,				"fake-roberta"				)
										os.makedirs(_SCREAMING_SNAKE_CASE		,				exist_ok=_SCREAMING_SNAKE_CASE				)
										with open(os.path.join(_SCREAMING_SNAKE_CASE		,				"config.json"				)		,				"w"				) as f:
												f.write(json.dumps({}				)				)
										snake_case_				:							int						 =       AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE				)
										self.assertEqual(type(_SCREAMING_SNAKE_CASE				)		,				_SCREAMING_SNAKE_CASE				)






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

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

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






						def       _lowerCAmelCase       (	self				) ->				int:
								with self.assertRaisesRegex(
								    _SCREAMING_SNAKE_CASE		,				"bert-base is not a local folder and is not a valid model identifier"				):
										snake_case_				:							Optional[Any]						 =       AutoConfig.from_pretrained("bert-base"				)






						def       _lowerCAmelCase       (	self				) ->				Tuple:
								with self.assertRaisesRegex(
								    _SCREAMING_SNAKE_CASE		,				r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"				):
										snake_case_				:							List[Any]						 =       AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE		,				revision="aaaaaa"				)






						def       _lowerCAmelCase       (	self				) ->				str:
								with self.assertRaisesRegex(
								    _SCREAMING_SNAKE_CASE		,				"hf-internal-testing/no-config-test-repo does not appear to have a file named config.json."		,				):
										snake_case_				:							Dict						 =       AutoConfig.from_pretrained("hf-internal-testing/no-config-test-repo"				)






						def       _lowerCAmelCase       (	self				) ->				Optional[int]:
								# If remote code is not set, we will time out when asking whether to load the model.
								with self.assertRaises(_SCREAMING_SNAKE_CASE				):
										snake_case_				:							Tuple						 =       AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"				)
								# If remote code is disabled, we can't load this config.
								with self.assertRaises(_SCREAMING_SNAKE_CASE				):
										snake_case_				:							Optional[Any]						 =       AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"		,				trust_remote_code=_SCREAMING_SNAKE_CASE				)

								snake_case_				:							List[Any]						 =       AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"		,				trust_remote_code=_SCREAMING_SNAKE_CASE				)
								self.assertEqual(config.__class__.__name__		,				"NewModelConfig"				)

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






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




								class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


														'''simple docstring'''




														A     :   List[Any]						=					'new-model'

								try:
										AutoConfig.register("new-model"		,				_SCREAMING_SNAKE_CASE				)
										# If remote code is not set, the default is to use local
										snake_case_				:							Union[str, 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_				:							Optional[Any]						 =       AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"		,				trust_remote_code=_SCREAMING_SNAKE_CASE				)
										self.assertEqual(config.__class__.__name__		,				"NewModelConfigLocal"				)

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

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