
"""simple docstring"""


import gc
import unittest

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

from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()




class  __lowerCamelCase  ( lowerCAmelCase						,	lowerCAmelCase						,	lowerCAmelCase						,	unittest.TestCase			):
				a__:      str          =    AltDiffusionPipeline
				a__:      List[str]          =    TEXT_TO_IMAGE_PARAMS
				a__:      Any          =    TEXT_TO_IMAGE_BATCH_PARAMS
				a__:      int          =    TEXT_TO_IMAGE_IMAGE_PARAMS
				a__:      Optional[int]          =    TEXT_TO_IMAGE_IMAGE_PARAMS




				def        UpperCAmelCase__						(				self   ):
							torch.manual_seed(0   )
							lowerCamelCase_					=  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							,						)
							lowerCamelCase_					=  DDIMScheduler(
							    beta_start=0.0_0_0_8_5							,						beta_end=0.0_1_2							,						beta_schedule='''scaled_linear'''							,						clip_sample=UpperCAmelCase							,						set_alpha_to_one=UpperCAmelCase							,						)
							torch.manual_seed(0   )
							lowerCamelCase_					=  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							,						)

							# TODO: address the non-deterministic text encoder (fails for save-load tests)
							# torch.manual_seed(0)
							# text_encoder_config = RobertaSeriesConfig(
							#     hidden_size=32,
							#     project_dim=32,
							#     intermediate_size=37,
							#     layer_norm_eps=1e-05,
							#     num_attention_heads=4,
							#     num_hidden_layers=5,
							#     vocab_size=5002,
							# )
							# text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config)

							torch.manual_seed(0   )
							lowerCamelCase_					=  CLIPTextConfig(
							    bos_token_id=0							,						eos_token_id=2							,						hidden_size=32							,						projection_dim=32							,						intermediate_size=37							,						layer_norm_eps=1e-0_5							,						num_attention_heads=4							,						num_hidden_layers=5							,						pad_token_id=1							,						vocab_size=5002							,						)
							lowerCamelCase_					=  CLIPTextModel(UpperCAmelCase   )

							lowerCamelCase_					=  XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta'''   )
							lowerCamelCase_					=  77

							lowerCamelCase_					=  {
							    '''unet''': unet,
							    '''scheduler''': scheduler,
							    '''vae''': vae,
							    '''text_encoder''': text_encoder,
							    '''tokenizer''': tokenizer,
							    '''safety_checker''': None,
							    '''feature_extractor''': None,
							}
							return components




				def        UpperCAmelCase__						(				self							,						UpperCAmelCase							,						UpperCAmelCase=0   ):
							if str(UpperCAmelCase   ).startswith('''mps'''   ):
										lowerCamelCase_					=  torch.manual_seed(UpperCAmelCase   )
							else:
										lowerCamelCase_					=  torch.Generator(device=UpperCAmelCase   ).manual_seed(UpperCAmelCase   )
							lowerCamelCase_					=  {
							    '''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        UpperCAmelCase__						(				self   ):
							super().test_attention_slicing_forward_pass(expected_max_diff=3e-3   )




				def        UpperCAmelCase__						(				self   ):
							super().test_inference_batch_single_identical(expected_max_diff=3e-3   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  '''cpu'''  # ensure determinism for the device-dependent torch.Generator

							lowerCamelCase_					=  self.get_dummy_components()
							torch.manual_seed(0   )
							lowerCamelCase_					=  RobertaSeriesConfig(
							    hidden_size=32							,						project_dim=32							,						intermediate_size=37							,						layer_norm_eps=1e-0_5							,						num_attention_heads=4							,						num_hidden_layers=5							,						vocab_size=5002							,						)
							# TODO: remove after fixing the non-deterministic text encoder
							lowerCamelCase_					=  RobertaSeriesModelWithTransformation(UpperCAmelCase   )
							lowerCamelCase_					=  text_encoder

							lowerCamelCase_					=  AltDiffusionPipeline(**UpperCAmelCase   )
							lowerCamelCase_					=  alt_pipe.to(UpperCAmelCase   )
							alt_pipe.set_progress_bar_config(disable=UpperCAmelCase   )

							lowerCamelCase_					=  self.get_dummy_inputs(UpperCAmelCase   )
							lowerCamelCase_					=  '''A photo of an astronaut'''
							lowerCamelCase_					=  alt_pipe(**UpperCAmelCase   )
							lowerCamelCase_					=  output.images
							lowerCamelCase_					=  image[0, -3:, -3:, -1]

							assert image.shape == (1, 64, 64, 3)
							lowerCamelCase_					=  np.array(
							    [0.5_7_4_8_1_6_2, 0.6_0_4_4_7_1_4_5, 0.4_8_8_2_1_2_1_7, 0.5_0_1_0_0_6_3_6, 0.5_4_3_1_1_8_5, 0.4_5_7_6_3_6_8_3, 0.4_9_6_5_7_6_9_6, 0.4_8_1_3_2_7_3_3, 0.4_7_5_7_3_0_9_3]   )

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





				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  '''cpu'''  # ensure determinism for the device-dependent torch.Generator

							lowerCamelCase_					=  self.get_dummy_components()
							lowerCamelCase_					=  PNDMScheduler(skip_prk_steps=UpperCAmelCase   )
							torch.manual_seed(0   )
							lowerCamelCase_					=  RobertaSeriesConfig(
							    hidden_size=32							,						project_dim=32							,						intermediate_size=37							,						layer_norm_eps=1e-0_5							,						num_attention_heads=4							,						num_hidden_layers=5							,						vocab_size=5002							,						)
							# TODO: remove after fixing the non-deterministic text encoder
							lowerCamelCase_					=  RobertaSeriesModelWithTransformation(UpperCAmelCase   )
							lowerCamelCase_					=  text_encoder
							lowerCamelCase_					=  AltDiffusionPipeline(**UpperCAmelCase   )
							lowerCamelCase_					=  alt_pipe.to(UpperCAmelCase   )
							alt_pipe.set_progress_bar_config(disable=UpperCAmelCase   )

							lowerCamelCase_					=  self.get_dummy_inputs(UpperCAmelCase   )
							lowerCamelCase_					=  alt_pipe(**UpperCAmelCase   )
							lowerCamelCase_					=  output.images
							lowerCamelCase_					=  image[0, -3:, -3:, -1]

							assert image.shape == (1, 64, 64, 3)
							lowerCamelCase_					=  np.array(
							    [0.5_1_6_0_5_0_9_3, 0.5_7_0_7_2_4_1, 0.4_7_3_6_5_5_0_7, 0.5_0_5_7_8_8_8_6, 0.5_6_3_3_8_7_7, 0.4_6_4_2_5_0_3, 0.5_1_8_2_0_8_1, 0.4_8_7_6_3_4_8_4, 0.4_9_0_8_4_2_3_7]   )

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




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




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




				def        UpperCAmelCase__						(				self   ):
							# make sure here that pndm scheduler skips prk
							lowerCamelCase_					=  AltDiffusionPipeline.from_pretrained('''BAAI/AltDiffusion'''							,						safety_checker=UpperCAmelCase   )
							lowerCamelCase_					=  alt_pipe.to(UpperCAmelCase   )
							alt_pipe.set_progress_bar_config(disable=UpperCAmelCase   )

							lowerCamelCase_					=  '''A painting of a squirrel eating a burger'''
							lowerCamelCase_					=  torch.manual_seed(0   )
							lowerCamelCase_					=  alt_pipe([prompt]							,						generator=UpperCAmelCase							,						guidance_scale=6.0							,						num_inference_steps=20							,						output_type='''np'''   )

							lowerCamelCase_					=  output.images

							lowerCamelCase_					=  image[0, -3:, -3:, -1]

							assert image.shape == (1, 512, 512, 3)
							lowerCamelCase_					=  np.array([0.1_0_1_0, 0.0_8_0_0, 0.0_7_9_4, 0.0_8_8_5, 0.0_8_4_3, 0.0_7_6_2, 0.0_7_6_9, 0.0_7_2_9, 0.0_5_8_6]   )

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





				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  DDIMScheduler.from_pretrained('''BAAI/AltDiffusion'''							,						subfolder='''scheduler'''   )

							lowerCamelCase_					=  AltDiffusionPipeline.from_pretrained('''BAAI/AltDiffusion'''							,						scheduler=UpperCAmelCase							,						safety_checker=UpperCAmelCase   )
							lowerCamelCase_					=  alt_pipe.to(UpperCAmelCase   )
							alt_pipe.set_progress_bar_config(disable=UpperCAmelCase   )

							lowerCamelCase_					=  '''A painting of a squirrel eating a burger'''
							lowerCamelCase_					=  torch.manual_seed(0   )

							lowerCamelCase_					=  alt_pipe([prompt]							,						generator=UpperCAmelCase							,						num_inference_steps=2							,						output_type='''numpy'''   )
							lowerCamelCase_					=  output.images

							lowerCamelCase_					=  image[0, -3:, -3:, -1]

							assert image.shape == (1, 512, 512, 3)
							lowerCamelCase_					=  np.array([0.4_0_1_9, 0.4_0_5_2, 0.3_8_1_0, 0.4_1_1_9, 0.3_9_1_6, 0.3_9_8_2, 0.4_6_5_1, 0.4_1_9_5, 0.5_3_2_3]   )

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





"""simple docstring"""


import copy
import tempfile
import unittest

from huggingface_hub import HfFolder, delete_repo
from parameterized import parameterized
from requests.exceptions import HTTPError

from transformers import AutoConfig, GenerationConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test




class  __lowerCamelCase  ( unittest.TestCase			):




				@parameterized.expand([(None,), ('''foo.json''',)]   )
				def        UpperCAmelCase__						(				self							,						UpperCAmelCase   ):
							lowerCamelCase_					=  GenerationConfig(
							    do_sample=UpperCAmelCase							,						temperature=0.7							,						length_penalty=1.0							,						bad_words_ids=[[1, 2, 3], [4, 5]]							,						)
							with tempfile.TemporaryDirectory() as tmp_dir:
										config.save_pretrained(UpperCAmelCase							,						config_name=UpperCAmelCase   )
										lowerCamelCase_					=  GenerationConfig.from_pretrained(UpperCAmelCase							,						config_name=UpperCAmelCase   )

							# Checks parameters that were specified
							self.assertEqual(loaded_config.do_sample							,						UpperCAmelCase   )
							self.assertEqual(loaded_config.temperature							,						0.7   )
							self.assertEqual(loaded_config.length_penalty							,						1.0   )
							self.assertEqual(loaded_config.bad_words_ids							,						[[1, 2, 3], [4, 5]]   )

							# Checks parameters that were not specified (defaults)
							self.assertEqual(loaded_config.top_k							,						50   )
							self.assertEqual(loaded_config.max_length							,						20   )
							self.assertEqual(loaded_config.max_time							,						UpperCAmelCase   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  AutoConfig.from_pretrained('''gpt2'''   )
							lowerCamelCase_					=  GenerationConfig.from_model_config(UpperCAmelCase   )
							lowerCamelCase_					=  GenerationConfig()

							# The generation config has loaded a few non-default parameters from the model config
							self.assertNotEqual(UpperCAmelCase							,						UpperCAmelCase   )

							# One of those parameters is eos_token_id -- check if it matches
							self.assertNotEqual(generation_config_from_model.eos_token_id							,						default_generation_config.eos_token_id   )
							self.assertEqual(generation_config_from_model.eos_token_id							,						model_config.eos_token_id   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  GenerationConfig()
							lowerCamelCase_					=  {
							    '''max_new_tokens''': 1024,
							    '''foo''': '''bar''',
							}
							lowerCamelCase_					=  copy.deepcopy(UpperCAmelCase   )
							lowerCamelCase_					=  generation_config.update(**UpperCAmelCase   )

							# update_kwargs was not modified (no side effects)
							self.assertEqual(UpperCAmelCase							,						UpperCAmelCase   )

							# update_kwargs was used to update the config on valid attributes
							self.assertEqual(generation_config.max_new_tokens							,						1024   )

							# `.update()` returns a dictionary of unused kwargs
							self.assertEqual(UpperCAmelCase							,						{'''foo''': '''bar'''}   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  GenerationConfig()
							lowerCamelCase_					=  '''bar'''

							with tempfile.TemporaryDirectory('''test-generation-config'''   ) as tmp_dir:
										generation_config.save_pretrained(UpperCAmelCase   )

										lowerCamelCase_					=  GenerationConfig.from_pretrained(UpperCAmelCase   )
							# update_kwargs was used to update the config on valid attributes
							self.assertEqual(new_config.foo							,						'''bar'''   )

							lowerCamelCase_					=  GenerationConfig.from_model_config(UpperCAmelCase   )
							assert not hasattr(UpperCAmelCase							,						'''foo'''   )  # no new kwargs should be initialized if from config





				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  GenerationConfig()
							self.assertEqual(default_config.temperature							,						1.0   )
							self.assertEqual(default_config.do_sample							,						UpperCAmelCase   )
							self.assertEqual(default_config.num_beams							,						1   )

							lowerCamelCase_					=  GenerationConfig(
							    do_sample=UpperCAmelCase							,						temperature=0.7							,						length_penalty=1.0							,						bad_words_ids=[[1, 2, 3], [4, 5]]							,						)
							self.assertEqual(config.temperature							,						0.7   )
							self.assertEqual(config.do_sample							,						UpperCAmelCase   )
							self.assertEqual(config.num_beams							,						1   )

							with tempfile.TemporaryDirectory() as tmp_dir:
										config.save_pretrained(UpperCAmelCase   )
										lowerCamelCase_					=  GenerationConfig.from_pretrained(UpperCAmelCase							,						temperature=1.0   )

							self.assertEqual(loaded_config.temperature							,						1.0   )
							self.assertEqual(loaded_config.do_sample							,						UpperCAmelCase   )
							self.assertEqual(loaded_config.num_beams							,						1   )  # default value




@is_staging_test
class  __lowerCamelCase  ( unittest.TestCase			):




				@classmethod
				def        UpperCAmelCase__						(				cls   ):
							lowerCamelCase_					=  TOKEN
							HfFolder.save_token(UpperCAmelCase   )




				@classmethod
				def        UpperCAmelCase__						(				cls   ):
							try:
										delete_repo(token=cls._token							,						repo_id='''test-generation-config'''   )
							except HTTPError:
										pass

							try:
										delete_repo(token=cls._token							,						repo_id='''valid_org/test-generation-config-org'''   )
							except HTTPError:
										pass




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  GenerationConfig(
							    do_sample=UpperCAmelCase							,						temperature=0.7							,						length_penalty=1.0							,						)
							config.push_to_hub('''test-generation-config'''							,						use_auth_token=self._token   )

							lowerCamelCase_					=  GenerationConfig.from_pretrained(f"{USER}/test-generation-config"   )
							for k, v in config.to_dict().items():
										if k != "transformers_version":
													self.assertEqual(UpperCAmelCase							,						getattr(UpperCAmelCase							,						UpperCAmelCase   )   )

        # Reset repo
							delete_repo(token=self._token							,						repo_id='''test-generation-config'''   )

							# Push to hub via save_pretrained
							with tempfile.TemporaryDirectory() as tmp_dir:
										config.save_pretrained(
										    UpperCAmelCase							,						repo_id='''test-generation-config'''							,						push_to_hub=UpperCAmelCase							,						use_auth_token=self._token   )

							lowerCamelCase_					=  GenerationConfig.from_pretrained(f"{USER}/test-generation-config"   )
							for k, v in config.to_dict().items():
										if k != "transformers_version":
													self.assertEqual(UpperCAmelCase							,						getattr(UpperCAmelCase							,						UpperCAmelCase   )   )





				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  GenerationConfig(
							    do_sample=UpperCAmelCase							,						temperature=0.7							,						length_penalty=1.0							,						)
							config.push_to_hub('''valid_org/test-generation-config-org'''							,						use_auth_token=self._token   )

							lowerCamelCase_					=  GenerationConfig.from_pretrained('''valid_org/test-generation-config-org'''   )
							for k, v in config.to_dict().items():
										if k != "transformers_version":
													self.assertEqual(UpperCAmelCase							,						getattr(UpperCAmelCase							,						UpperCAmelCase   )   )

        # Reset repo
							delete_repo(token=self._token							,						repo_id='''valid_org/test-generation-config-org'''   )

							# Push to hub via save_pretrained
							with tempfile.TemporaryDirectory() as tmp_dir:
										config.save_pretrained(
										    UpperCAmelCase							,						repo_id='''valid_org/test-generation-config-org'''							,						push_to_hub=UpperCAmelCase							,						use_auth_token=self._token   )

							lowerCamelCase_					=  GenerationConfig.from_pretrained('''valid_org/test-generation-config-org'''   )
							for k, v in config.to_dict().items():
										if k != "transformers_version":
													self.assertEqual(UpperCAmelCase							,						getattr(UpperCAmelCase							,						UpperCAmelCase   )   )



