




"""simple docstring"""







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       lowerCAmelCase__       (			unittest.TestCase    ):


				"""simple docstring"""





				def       snake_case    (     self					:	List[str]						):
						# clean up the VRAM after each test
						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()



				@property
				def       snake_case    (     self					:	Optional[int]						):
						__lowercase				:		Union[str, Any]												=				1
						__lowercase				:		Dict												=				3
						__lowercase				:		str												=				(3_2, 3_2)

						__lowercase				:		List[Any]												=				floats_tensor((batch_size, num_channels) + sizes    ,   rng=random.Random(0						)						).to(lowercase__						)
						return image



				@property
				def       snake_case    (     self					:	List[str]						):
						torch.manual_seed(0						)
						__lowercase				:		Union[str, Any]												=				UNetaDConditionModel(
						    block_out_channels=(3_2, 6_4)    ,   layers_per_block=2    ,   sample_size=3_2    ,   in_channels=4    ,   out_channels=4    ,   down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")    ,   up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")    ,   cross_attention_dim=3_2    ,   )
						return model



				@property
				def       snake_case    (     self					:	Dict						):
						torch.manual_seed(0						)
						__lowercase				:		Union[str, Any]												=				AutoencoderKL(
						    block_out_channels=[3_2, 6_4]    ,   in_channels=3    ,   out_channels=3    ,   down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]    ,   up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]    ,   latent_channels=4    ,   )
						return model



				@property
				def       snake_case    (     self					:	int						):
						torch.manual_seed(0						)
						__lowercase				:		str												=				RobertaSeriesConfig(
						    hidden_size=3_2    ,   project_dim=3_2    ,   intermediate_size=3_7    ,   layer_norm_eps=1e-05    ,   num_attention_heads=4    ,   num_hidden_layers=5    ,   pad_token_id=1    ,   vocab_size=5_0_0_6    ,   )
						return RobertaSeriesModelWithTransformation(lowercase__						)



				@property
				def       snake_case    (     self					:	Any						):
						def extract(*lowercase__					:	Any    ,   **lowercase__					:	List[Any]						):




								class       lowerCAmelCase__       :


												"""simple docstring"""





												def __init__(     self					:	Tuple						):
														__lowercase				:		Dict												=				torch.ones([0]						)



												def       snake_case    (     self					:	Tuple    ,   lowercase__					:	Optional[int]						):
														self.pixel_values.to(lowercase__						)
														return self





								return Out()

						return extract



				def       snake_case    (     self					:	List[str]						):
						__lowercase				:		Dict												=				"cpu"  # ensure determinism for the device-dependent torch.Generator
						__lowercase				:		Optional[Any]												=				self.dummy_cond_unet
						__lowercase				:		int												=				PNDMScheduler(skip_prk_steps=lowercase__						)
						__lowercase				:		Union[str, Any]												=				self.dummy_vae
						__lowercase				:		List[Any]												=				self.dummy_text_encoder
						__lowercase				:		str												=				XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta"						)
						__lowercase				:		Optional[Any]												=				7_7

						__lowercase				:		Optional[Any]												=				self.dummy_image.to(lowercase__						)
						__lowercase				:		List[Any]												=				init_image / 2 + 0.5

						# make sure here that pndm scheduler skips prk
						__lowercase				:		Dict												=				AltDiffusionImgaImgPipeline(
						    unet=lowercase__    ,   scheduler=lowercase__    ,   vae=lowercase__    ,   text_encoder=lowercase__    ,   tokenizer=lowercase__    ,   safety_checker=lowercase__    ,   feature_extractor=self.dummy_extractor    ,   )
						__lowercase				:		str												=				VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor    ,   do_normalize=lowercase__						)
						__lowercase				:		str												=				alt_pipe.to(lowercase__						)
						alt_pipe.set_progress_bar_config(disable=lowercase__						)

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

						__lowercase				:		List[str]												=				output.images

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

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

						assert image.shape == (1, 3_2, 3_2, 3)
						__lowercase				:		Any												=				np.array([0.4_4_2_7, 0.3_7_3_1, 0.4_2_4_9, 0.4_9_4_1, 0.4_5_4_6, 0.4_1_4_8, 0.4_1_9_3, 0.4_6_6_6, 0.4_4_9_9]						)

						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       snake_case    (     self					:	Any						):
						__lowercase				:		Optional[Any]												=				self.dummy_cond_unet
						__lowercase				:		Tuple												=				PNDMScheduler(skip_prk_steps=lowercase__						)
						__lowercase				:		Union[str, Any]												=				self.dummy_vae
						__lowercase				:		Any												=				self.dummy_text_encoder
						__lowercase				:		List[Any]												=				XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta"						)
						__lowercase				:		List[str]												=				7_7

						__lowercase				:		Any												=				self.dummy_image.to(lowercase__						)

						# put models in fp16
						__lowercase				:		Optional[Any]												=				unet.half()
						__lowercase				:		Dict												=				vae.half()
						__lowercase				:		List[str]												=				bert.half()

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

						__lowercase				:		Dict												=				"A painting of a squirrel eating a burger"
						__lowercase				:		Tuple												=				torch.manual_seed(0						)
						__lowercase				:		str												=				alt_pipe(
						    [prompt]    ,   generator=lowercase__    ,   num_inference_steps=2    ,   output_type="np"    ,   image=lowercase__    ,   ).images

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



				@unittest.skipIf(torch_device != "cuda"    ,   "This test requires a GPU"						)
				def       snake_case    (     self					:	List[Any]						):
						__lowercase				:		Any												=				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
						__lowercase				:		Optional[Any]												=				init_image.resize((7_6_0, 5_0_4)						)

						__lowercase				:		List[str]												=				"BAAI/AltDiffusion"
						__lowercase				:		Tuple												=				AltDiffusionImgaImgPipeline.from_pretrained(
						    lowercase__    ,   safety_checker=lowercase__    ,   )
						pipe.to(lowercase__						)
						pipe.set_progress_bar_config(disable=lowercase__						)
						pipe.enable_attention_slicing()

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

						__lowercase				:		str												=				torch.manual_seed(0						)
						__lowercase				:		List[str]												=				pipe(
						    prompt=lowercase__    ,   image=lowercase__    ,   strength=0.7_5    ,   guidance_scale=7.5    ,   generator=lowercase__    ,   output_type="np"    ,   )
						__lowercase				:		int												=				output.images[0]

						__lowercase				:		Dict												=				image[2_5_5:2_5_8, 3_8_3:3_8_6, -1]

						assert image.shape == (5_0_4, 7_6_0, 3)
						__lowercase				:		Union[str, Any]												=				np.array([0.9_3_5_8, 0.9_3_9_7, 0.9_5_9_9, 0.9_9_0_1, 1.0_0_0_0, 1.0_0_0_0, 0.9_8_8_2, 1.0_0_0_0, 1.0_0_0_0]						)

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





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


				"""simple docstring"""





				def       snake_case    (     self					:	Optional[int]						):
						# clean up the VRAM after each test
						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()



				def       snake_case    (     self					:	Union[str, Any]						):
						__lowercase				:		List[Any]												=				load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
						    "/img2img/sketch-mountains-input.jpg"						)
						__lowercase				:		str												=				init_image.resize((7_6_8, 5_1_2)						)
						__lowercase				:		Optional[int]												=				load_numpy(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"						)

						__lowercase				:		str												=				"BAAI/AltDiffusion"
						__lowercase				:		int												=				AltDiffusionImgaImgPipeline.from_pretrained(
						    lowercase__    ,   safety_checker=lowercase__    ,   )
						pipe.to(lowercase__						)
						pipe.set_progress_bar_config(disable=lowercase__						)
						pipe.enable_attention_slicing()

						__lowercase				:		int												=				"A fantasy landscape, trending on artstation"

						__lowercase				:		str												=				torch.manual_seed(0						)
						__lowercase				:		str												=				pipe(
						    prompt=lowercase__    ,   image=lowercase__    ,   strength=0.7_5    ,   guidance_scale=7.5    ,   generator=lowercase__    ,   output_type="np"    ,   )
						__lowercase				:		Tuple												=				output.images[0]

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






"""simple docstring"""







import unittest

from transformers import EsmConfig, is_torch_available
from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch

						from transformers.models.esm.modeling_esmfold import EsmForProteinFolding




class       lowerCAmelCase__       :


				"""simple docstring"""





				def __init__(     self					:	Tuple    ,   lowercase__					:	Tuple    ,   lowercase__					:	Tuple=1_3    ,   lowercase__					:	Optional[int]=7    ,   lowercase__					:	List[str]=False    ,   lowercase__					:	Tuple=True    ,   lowercase__					:	int=False    ,   lowercase__					:	List[str]=False    ,   lowercase__					:	Optional[Any]=1_9    ,   lowercase__					:	int=3_2    ,   lowercase__					:	List[Any]=5    ,   lowercase__					:	Optional[int]=4    ,   lowercase__					:	Any=3_7    ,   lowercase__					:	Tuple="gelu"    ,   lowercase__					:	int=0.1    ,   lowercase__					:	Tuple=0.1    ,   lowercase__					:	List[Any]=5_1_2    ,   lowercase__					:	List[Any]=1_6    ,   lowercase__					:	Union[str, Any]=2    ,   lowercase__					:	List[str]=0.0_2    ,   lowercase__					:	List[Any]=3    ,   lowercase__					:	Any=4    ,   lowercase__					:	Optional[Any]=None    ,   ):
						__lowercase				:		int												=				parent
						__lowercase				:		Tuple												=				batch_size
						__lowercase				:		Optional[int]												=				seq_length
						__lowercase				:		str												=				is_training
						__lowercase				:		List[Any]												=				use_input_mask
						__lowercase				:		Any												=				use_token_type_ids
						__lowercase				:		str												=				use_labels
						__lowercase				:		Dict												=				vocab_size
						__lowercase				:		Optional[int]												=				hidden_size
						__lowercase				:		List[Any]												=				num_hidden_layers
						__lowercase				:		int												=				num_attention_heads
						__lowercase				:		Union[str, Any]												=				intermediate_size
						__lowercase				:		Dict												=				hidden_act
						__lowercase				:		Union[str, Any]												=				hidden_dropout_prob
						__lowercase				:		Optional[int]												=				attention_probs_dropout_prob
						__lowercase				:		Optional[Any]												=				max_position_embeddings
						__lowercase				:		List[str]												=				type_vocab_size
						__lowercase				:		str												=				type_sequence_label_size
						__lowercase				:		List[str]												=				initializer_range
						__lowercase				:		Optional[Any]												=				num_labels
						__lowercase				:		Tuple												=				num_choices
						__lowercase				:		Optional[Any]												=				scope



				def       snake_case    (     self					:	Optional[int]						):
						__lowercase				:		Tuple												=				ids_tensor([self.batch_size, self.seq_length]    ,   self.vocab_size						)

						__lowercase				:		Union[str, Any]												=				None
						if self.use_input_mask:
								__lowercase				:		List[str]												=				random_attention_mask([self.batch_size, self.seq_length]						)

						__lowercase				:		Dict												=				None
						__lowercase				:		Any												=				None
						__lowercase				:		Optional[Any]												=				None
						if self.use_labels:
								__lowercase				:		Tuple												=				ids_tensor([self.batch_size]    ,   self.type_sequence_label_size						)
								__lowercase				:		List[str]												=				ids_tensor([self.batch_size, self.seq_length]    ,   self.num_labels						)
								__lowercase				:		Optional[Any]												=				ids_tensor([self.batch_size]    ,   self.num_choices						)

						__lowercase				:		Optional[Any]												=				self.get_config()

						return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels



				def       snake_case    (     self					:	Any						):
						__lowercase				:		Dict												=				EsmConfig(
						    vocab_size=3_3    ,   hidden_size=self.hidden_size    ,   pad_token_id=1    ,   num_hidden_layers=self.num_hidden_layers    ,   num_attention_heads=self.num_attention_heads    ,   intermediate_size=self.intermediate_size    ,   hidden_act=self.hidden_act    ,   hidden_dropout_prob=self.hidden_dropout_prob    ,   attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,   max_position_embeddings=self.max_position_embeddings    ,   type_vocab_size=self.type_vocab_size    ,   initializer_range=self.initializer_range    ,   is_folding_model=lowercase__    ,   esmfold_config={"trunk": {"num_blocks": 2}, "fp16_esm": False}    ,   )
						return config



				def       snake_case    (     self					:	str    ,   lowercase__					:	List[Any]    ,   lowercase__					:	Optional[int]    ,   lowercase__					:	List[Any]    ,   lowercase__					:	int    ,   lowercase__					:	List[Any]    ,   lowercase__					:	str						):
						__lowercase				:		List[Any]												=				EsmForProteinFolding(config=lowercase__						).float()
						model.to(lowercase__						)
						model.eval()
						__lowercase				:		List[str]												=				model(lowercase__    ,   attention_mask=lowercase__						)
						__lowercase				:		Any												=				model(lowercase__						)
						__lowercase				:		Any												=				model(lowercase__						)

						self.parent.assertEqual(result.positions.shape    ,   (8, self.batch_size, self.seq_length, 1_4, 3)						)
						self.parent.assertEqual(result.angles.shape    ,   (8, self.batch_size, self.seq_length, 7, 2)						)



				def       snake_case    (     self					:	Tuple						):
						__lowercase				:		List[str]												=				self.prepare_config_and_inputs()
						(
						    (
						    __lowercase
						)						,(
						    __lowercase
						)						,(
						    __lowercase
						)						,(
						    __lowercase
						)						,(
						    __lowercase
						)						,(
						    __lowercase
						)						,
						)				:		Any												=				config_and_inputs
						__lowercase				:		int												=				{"input_ids": input_ids, "attention_mask": input_mask}
						return config, inputs_dict





@require_torch
class       lowerCAmelCase__       (			lowerCAmelCase_  ,			lowerCAmelCase_  ,			unittest.TestCase    ):


				"""simple docstring"""





				__UpperCAmelCase :     Union[str, Any]       =      False

				__UpperCAmelCase :     List[Any]       =      (EsmForProteinFolding,) if is_torch_available() else ()
				__UpperCAmelCase :     int       =      ()
				__UpperCAmelCase :     Tuple       =      {} if is_torch_available() else {}
				__UpperCAmelCase :     Optional[Any]       =      False



				def       snake_case    (     self					:	Tuple						):
						__lowercase				:		Tuple												=				EsmFoldModelTester(self						)
						__lowercase				:		Dict												=				ConfigTester(self    ,   config_class=lowercase__    ,   hidden_size=3_7						)



				def       snake_case    (     self					:	Dict						):
						self.config_tester.run_common_tests()



				def       snake_case    (     self					:	Optional[int]						):
						__lowercase				:		Tuple												=				self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*lowercase__						)



				@unittest.skip("Does not support attention outputs"						)
				def       snake_case    (     self					:	Union[str, Any]						):
						pass



				@unittest.skip
				def       snake_case    (     self					:	Tuple						):
						pass



				@unittest.skip("Esm does not support embedding resizing"						)
				def       snake_case    (     self					:	Optional[int]						):
						pass



				@unittest.skip("Esm does not support embedding resizing"						)
				def       snake_case    (     self					:	List[str]						):
						pass



				@unittest.skip("ESMFold does not support passing input embeds!"						)
				def       snake_case    (     self					:	int						):
						pass



				@unittest.skip("ESMFold does not support head pruning."						)
				def       snake_case    (     self					:	List[Any]						):
						pass



				@unittest.skip("ESMFold does not support head pruning."						)
				def       snake_case    (     self					:	Any						):
						pass



				@unittest.skip("ESMFold does not support head pruning."						)
				def       snake_case    (     self					:	Optional[Any]						):
						pass



				@unittest.skip("ESMFold does not support head pruning."						)
				def       snake_case    (     self					:	List[str]						):
						pass



				@unittest.skip("ESMFold does not support head pruning."						)
				def       snake_case    (     self					:	List[str]						):
						pass



				@unittest.skip("ESMFold does not output hidden states in the normal way."						)
				def       snake_case    (     self					:	Optional[Any]						):
						pass



				@unittest.skip("ESMfold does not output hidden states in the normal way."						)
				def       snake_case    (     self					:	Optional[Any]						):
						pass



				@unittest.skip("ESMFold only has one output format."						)
				def       snake_case    (     self					:	Tuple						):
						pass



				@unittest.skip("This test doesn't work for ESMFold and doesn't test core functionality"						)
				def       snake_case    (     self					:	Any						):
						pass



				@unittest.skip("ESMFold does not support input chunking."						)
				def       snake_case    (     self					:	str						):
						pass



				@unittest.skip("ESMFold doesn't respect you and it certainly doesn't respect your initialization arguments."						)
				def       snake_case    (     self					:	Any						):
						pass



				@unittest.skip("ESMFold doesn't support torchscript compilation."						)
				def       snake_case    (     self					:	Any						):
						pass



				@unittest.skip("ESMFold doesn't support torchscript compilation."						)
				def       snake_case    (     self					:	Tuple						):
						pass



				@unittest.skip("ESMFold doesn't support torchscript compilation."						)
				def       snake_case    (     self					:	List[str]						):
						pass



				@unittest.skip("ESMFold doesn't support data parallel."						)
				def       snake_case    (     self					:	Optional[Any]						):
						pass



				@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."						)
				def       snake_case    (     self					:	Any						):
						pass





@require_torch
class       lowerCAmelCase__       (			lowerCAmelCase_    ):


				"""simple docstring"""





				@slow
				def       snake_case    (     self					:	Union[str, Any]						):
						__lowercase				:		Tuple												=				EsmForProteinFolding.from_pretrained("facebook/esmfold_v1"						).float()
						model.eval()
						__lowercase				:		Optional[int]												=				torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]]						)
						__lowercase				:		str												=				model(lowercase__						)["positions"]
						__lowercase				:		Union[str, Any]												=				torch.tensor([2.5_8_2_8, 0.7_9_9_3, -1_0.9_3_3_4]    ,   dtype=torch.floataa						)
						self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0]    ,   lowercase__    ,   atol=1e-4						)						)
