




"""simple docstring"""





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


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



class      a__				(	unittest.TestCase   ):


			def       a_     (      self      :    Optional[int]):


						"""simple docstring"""




						__UpperCAmelCase	: Any		=					0


			def       a_     (      self      :    List[Any]):


						"""simple docstring"""




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


			def       a_     (      self      :    int):


						"""simple docstring"""




						__UpperCAmelCase	: int		=					AutoConfig.from_pretrained("bert-base-uncased")
						self.assertIsInstance(UpperCamelCase_      ,  UpperCamelCase_)


			def       a_     (      self      :    List[Any]):


						"""simple docstring"""




						__UpperCAmelCase	: List[str]		=					AutoConfig.from_pretrained(UpperCamelCase_)
						self.assertIsInstance(UpperCamelCase_      ,  UpperCamelCase_)


			def       a_     (      self      :    str):


						"""simple docstring"""




						__UpperCAmelCase	: Dict		=					AutoConfig.from_pretrained(UpperCamelCase_)
						self.assertIsInstance(UpperCamelCase_      ,  UpperCamelCase_)


			def       a_     (      self      :    Dict):


						"""simple docstring"""




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


			def       a_     (      self      :    Union[str, Any]):


						"""simple docstring"""




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


			def       a_     (      self      :    str):


						"""simple docstring"""




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

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

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


			def       a_     (      self      :    List[Any]):


						"""simple docstring"""




						with self.assertRaisesRegex(
						    UpperCamelCase_      ,  "bert-base is not a local folder and is not a valid model identifier"):
									__UpperCAmelCase	: List[str]		=					AutoConfig.from_pretrained("bert-base")


			def       a_     (      self      :    Optional[Any]):


						"""simple docstring"""




						with self.assertRaisesRegex(
						    UpperCamelCase_      ,  r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"):
									__UpperCAmelCase	: Any		=					AutoConfig.from_pretrained(UpperCamelCase_      ,  revision="aaaaaa")


			def       a_     (      self      :    Optional[int]):


						"""simple docstring"""




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


			def       a_     (      self      :    Any):


						"""simple docstring"""




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

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

						# Test config can be reloaded.
						with tempfile.TemporaryDirectory() as tmp_dir:
									config.save_pretrained(UpperCamelCase_)
									__UpperCAmelCase	: Dict		=					AutoConfig.from_pretrained(UpperCamelCase_      ,  trust_remote_code=UpperCamelCase_)
						self.assertEqual(reloaded_config.__class__.__name__      ,  "NewModelConfig")


			def       a_     (      self      :    List[str]):


						"""simple docstring"""




						class      a__				(	__magic_name__   ):
									lowercase_    =	"new-model"

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

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

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








"""simple docstring"""





import gc
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



class      a__				(	__magic_name__							,    unittest.TestCase   ):
			lowercase_    =	LDMTextToImagePipeline
			lowercase_    =	TEXT_TO_IMAGE_PARAMS - {
			    "negative_prompt",
			    "negative_prompt_embeds",
			    "cross_attention_kwargs",
			    "prompt_embeds",
			}
			lowercase_    =	PipelineTesterMixin.required_optional_params - {
			    "num_images_per_prompt",
			    "callback",
			    "callback_steps",
			}
			lowercase_    =	TEXT_TO_IMAGE_BATCH_PARAMS
			lowercase_    =	False


			def       a_     (      self      :    Union[str, Any]):


						"""simple docstring"""




						torch.manual_seed(0)
						__UpperCAmelCase	: str		=					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      ,  )
						__UpperCAmelCase	: Dict		=					DDIMScheduler(
						    beta_start=0.00085      ,  beta_end=0.012      ,  beta_schedule="scaled_linear"      ,  clip_sample=UpperCamelCase_      ,  set_alpha_to_one=UpperCamelCase_      ,  )
						torch.manual_seed(0)
						__UpperCAmelCase	: Optional[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      ,  )
						torch.manual_seed(0)
						__UpperCAmelCase	: List[str]		=					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      ,  )
						__UpperCAmelCase	: List[str]		=					CLIPTextModel(UpperCamelCase_)
						__UpperCAmelCase	: Union[str, Any]		=					CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")

						__UpperCAmelCase	: Optional[int]		=					{
						    "unet": unet,
						    "scheduler": scheduler,
						    "vqvae": vae,
						    "bert": text_encoder,
						    "tokenizer": tokenizer,
						}
						return components


			def       a_     (      self      :    Tuple      ,  UpperCamelCase_      :    Optional[Any]      ,  UpperCamelCase_      :    Tuple=0):


						"""simple docstring"""




						if str(UpperCamelCase_).startswith("mps"):
									__UpperCAmelCase	: str		=					torch.manual_seed(UpperCamelCase_)
						else:
									__UpperCAmelCase	: Tuple		=					torch.Generator(device=UpperCamelCase_).manual_seed(UpperCamelCase_)
						__UpperCAmelCase	: Tuple		=					{
						    "prompt": "A painting of a squirrel eating a burger",
						    "generator": generator,
						    "num_inference_steps": 2,
						    "guidance_scale": 6.0,
						    "output_type": "numpy",
						}
						return inputs


			def       a_     (      self      :    Tuple):


						"""simple docstring"""




						__UpperCAmelCase	: Any		=					"cpu"  # ensure determinism for the device-dependent torch.Generator

						__UpperCAmelCase	: Union[str, Any]		=					self.get_dummy_components()
						__UpperCAmelCase	: Union[str, Any]		=					LDMTextToImagePipeline(**UpperCamelCase_)
						pipe.to(UpperCamelCase_)
						pipe.set_progress_bar_config(disable=UpperCamelCase_)

						__UpperCAmelCase	: int		=					self.get_dummy_inputs(UpperCamelCase_)
						__UpperCAmelCase	: Dict		=					pipe(**UpperCamelCase_).images
						__UpperCAmelCase	: List[Any]		=					image[0, -3:, -3:, -1]

						assert image.shape == (1, 16, 16, 3)
						__UpperCAmelCase	: List[str]		=					np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014])

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






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


			def       a_     (      self      :    Optional[int]):


						"""simple docstring"""




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


			def       a_     (      self      :    List[str]      ,  UpperCamelCase_      :    str      ,  UpperCamelCase_      :    int=torch.floataa      ,  UpperCamelCase_      :    Dict=0):


						"""simple docstring"""




						__UpperCAmelCase	: Optional[Any]		=					torch.manual_seed(UpperCamelCase_)
						__UpperCAmelCase	: Optional[Any]		=					np.random.RandomState(UpperCamelCase_).standard_normal((1, 4, 32, 32))
						__UpperCAmelCase	: str		=					torch.from_numpy(UpperCamelCase_).to(device=UpperCamelCase_      ,  dtype=UpperCamelCase_)
						__UpperCAmelCase	: Tuple		=					{
						    "prompt": "A painting of a squirrel eating a burger",
						    "latents": latents,
						    "generator": generator,
						    "num_inference_steps": 3,
						    "guidance_scale": 6.0,
						    "output_type": "numpy",
						}
						return inputs


			def       a_     (      self      :    Optional[int]):


						"""simple docstring"""




						__UpperCAmelCase	: str		=					LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256").to(UpperCamelCase_)
						pipe.set_progress_bar_config(disable=UpperCamelCase_)

						__UpperCAmelCase	: Optional[int]		=					self.get_inputs(UpperCamelCase_)
						__UpperCAmelCase	: Union[str, Any]		=					pipe(**UpperCamelCase_).images
						__UpperCAmelCase	: Dict		=					image[0, -3:, -3:, -1].flatten()

						assert image.shape == (1, 256, 256, 3)
						__UpperCAmelCase	: List[Any]		=					np.array([0.51825, 0.52850, 0.52543, 0.54258, 0.52304, 0.52569, 0.54363, 0.55276, 0.56878])
						__UpperCAmelCase	: List[Any]		=					np.abs(expected_slice - image_slice).max()
						assert max_diff < 1e-3






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


			def       a_     (      self      :    Optional[Any]):


						"""simple docstring"""




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


			def       a_     (      self      :    Tuple      ,  UpperCamelCase_      :    Tuple      ,  UpperCamelCase_      :    int=torch.floataa      ,  UpperCamelCase_      :    Optional[int]=0):


						"""simple docstring"""




						__UpperCAmelCase	: str		=					torch.manual_seed(UpperCamelCase_)
						__UpperCAmelCase	: Tuple		=					np.random.RandomState(UpperCamelCase_).standard_normal((1, 4, 32, 32))
						__UpperCAmelCase	: Optional[Any]		=					torch.from_numpy(UpperCamelCase_).to(device=UpperCamelCase_      ,  dtype=UpperCamelCase_)
						__UpperCAmelCase	: Dict		=					{
						    "prompt": "A painting of a squirrel eating a burger",
						    "latents": latents,
						    "generator": generator,
						    "num_inference_steps": 50,
						    "guidance_scale": 6.0,
						    "output_type": "numpy",
						}
						return inputs


			def       a_     (      self      :    Dict):


						"""simple docstring"""




						__UpperCAmelCase	: str		=					LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256").to(UpperCamelCase_)
						pipe.set_progress_bar_config(disable=UpperCamelCase_)

						__UpperCAmelCase	: Union[str, Any]		=					self.get_inputs(UpperCamelCase_)
						__UpperCAmelCase	: List[str]		=					pipe(**UpperCamelCase_).images[0]

						__UpperCAmelCase	: int		=					load_numpy(
						    "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy")
						__UpperCAmelCase	: int		=					np.abs(expected_image - image).max()
						assert max_diff < 1e-3


