


"""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 import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel
		from transformers.models.esm.modeling_esm import (
		    ESM_PRETRAINED_MODEL_ARCHIVE_LIST,
		    EsmEmbeddings,
		    create_position_ids_from_input_ids,
		)
class snake_case      :







		def __init__(					self      :       Dict    ,   a__      :       Tuple    ,   a__      :       Optional[Any]=13    ,   a__      :       Tuple=7    ,   a__      :       Tuple=False    ,   a__      :       Tuple=True    ,   a__      :       Union[str, Any]=False    ,   a__      :       Optional[int]=True    ,   a__      :       Tuple=33    ,   a__      :       Union[str, Any]=32    ,   a__      :       List[Any]=5    ,   a__      :       Optional[Any]=4    ,   a__      :       List[str]=37    ,   a__      :       Optional[int]="gelu"    ,   a__      :       Tuple=0.1    ,   a__      :       str=0.1    ,   a__      :       str=5_12    ,   a__      :       Optional[int]=16    ,   a__      :       List[Any]=2    ,   a__      :       str=0.0_2    ,   a__      :       int=3    ,   a__      :       str=4    ,   a__      :       List[Any]=None    ,   )       ->						int:





						'''simple docstring'''







						_A					  =			parent
						_A					  =			batch_size
						_A					  =			seq_length
						_A					  =			is_training
						_A					  =			use_input_mask
						_A					  =			use_token_type_ids
						_A					  =			use_labels
						_A					  =			vocab_size
						_A					  =			hidden_size
						_A					  =			num_hidden_layers
						_A					  =			num_attention_heads
						_A					  =			intermediate_size
						_A					  =			hidden_act
						_A					  =			hidden_dropout_prob
						_A					  =			attention_probs_dropout_prob
						_A					  =			max_position_embeddings
						_A					  =			type_vocab_size
						_A					  =			type_sequence_label_size
						_A					  =			initializer_range
						_A					  =			num_labels
						_A					  =			num_choices
						_A					  =			scope







		def  a_ (					self      :       Any		)       ->						Dict:





						'''simple docstring'''







						_A					  =			ids_tensor([self.batch_size, self.seq_length]    ,   self.vocab_size		)

						_A					  =			None
						if self.use_input_mask:
										_A					  =			random_attention_mask([self.batch_size, self.seq_length]		)

						_A					  =			None
						_A					  =			None
						_A					  =			None
						if self.use_labels:
										_A					  =			ids_tensor([self.batch_size]    ,   self.type_sequence_label_size		)
										_A					  =			ids_tensor([self.batch_size, self.seq_length]    ,   self.num_labels		)
										_A					  =			ids_tensor([self.batch_size]    ,   self.num_choices		)

						_A					  =			self.get_config()

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







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





						'''simple docstring'''







						return EsmConfig(
						    vocab_size=self.vocab_size    ,   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    ,   )







		def  a_ (					self      :       Union[str, Any]    ,   a__      :       str    ,   a__      :       List[Any]    ,   a__      :       List[str]    ,   a__      :       Dict    ,   a__      :       int    ,   a__      :       Optional[Any]		)       ->						int:





						'''simple docstring'''







						_A					  =			EsmModel(config=__lowerCamelCase		)
						model.to(__lowerCamelCase		)
						model.eval()
						_A					  =			model(__lowerCamelCase    ,   attention_mask=__lowerCamelCase		)
						_A					  =			model(__lowerCamelCase		)
						_A					  =			model(__lowerCamelCase		)

						self.parent.assertEqual(result.last_hidden_state.shape    ,   (self.batch_size, self.seq_length, self.hidden_size)		)
						self.parent.assertEqual(result.pooler_output.shape    ,   (self.batch_size, self.hidden_size)		)







		def  a_ (					self      :       Tuple    ,   a__      :       Dict    ,   a__      :       Optional[Any]    ,   a__      :       Union[str, Any]    ,   a__      :       str    ,   a__      :       Optional[Any]    ,   a__      :       str		)       ->						int:





						'''simple docstring'''







						_A					  =			EsmForMaskedLM(config=__lowerCamelCase		)
						model.to(__lowerCamelCase		)
						model.eval()
						_A					  =			model(__lowerCamelCase    ,   attention_mask=__lowerCamelCase    ,   labels=__lowerCamelCase		)
						self.parent.assertEqual(result.logits.shape    ,   (self.batch_size, self.seq_length, self.vocab_size)		)







		def  a_ (					self      :       Optional[int]    ,   a__      :       Tuple    ,   a__      :       str    ,   a__      :       List[str]    ,   a__      :       List[str]    ,   a__      :       int    ,   a__      :       List[str]		)       ->						List[Any]:





						'''simple docstring'''







						_A					  =			self.num_labels
						_A					  =			EsmForTokenClassification(config=__lowerCamelCase		)
						model.to(__lowerCamelCase		)
						model.eval()
						_A					  =			model(__lowerCamelCase    ,   attention_mask=__lowerCamelCase    ,   labels=__lowerCamelCase		)
						self.parent.assertEqual(result.logits.shape    ,   (self.batch_size, self.seq_length, self.num_labels)		)







		def  a_ (					self      :       Optional[int]		)       ->						Dict:





						'''simple docstring'''







						_A					  =			self.prepare_config_and_inputs()
						(
						    _A	
						)					  =			config_and_inputs
						_A					  =			{'''input_ids''': input_ids, '''attention_mask''': input_mask}
						return config, inputs_dict





@require_torch
class snake_case      (  lowerCamelCase__     ,				lowerCamelCase__     ,				unittest.TestCase):
		__UpperCamelCase           =			False

		__UpperCamelCase           =			(
		    (
		        EsmForMaskedLM,
		        EsmModel,
		        EsmForSequenceClassification,
		        EsmForTokenClassification,
		    )
		    if is_torch_available()
		    else ()
		)
		__UpperCamelCase           =			()
		__UpperCamelCase           =			(
		    {
		        'feature-extraction': EsmModel,
		        'fill-mask': EsmForMaskedLM,
		        'text-classification': EsmForSequenceClassification,
		        'token-classification': EsmForTokenClassification,
		        'zero-shot': EsmForSequenceClassification,
		    }
		    if is_torch_available()
		    else {}
		)
		__UpperCamelCase           =			True







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





						'''simple docstring'''







						_A					  =			EsmModelTester(self		)
						_A					  =			ConfigTester(self    ,   config_class=__lowerCamelCase    ,   hidden_size=37		)







		def  a_ (					self      :       List[str]		)       ->						Optional[int]:





						'''simple docstring'''







						self.config_tester.run_common_tests()







		def  a_ (					self      :       Tuple		)       ->						Any:





						'''simple docstring'''







						_A					  =			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__lowerCamelCase		)







		def  a_ (					self      :       int		)       ->						Any:





						'''simple docstring'''







						_A					  =			self.model_tester.prepare_config_and_inputs()
						for type in ["absolute", "relative_key", "relative_key_query"]:
										_A					  =			type
										self.model_tester.create_and_check_model(*__lowerCamelCase		)







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





						'''simple docstring'''







						_A					  =			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_masked_lm(*__lowerCamelCase		)







		def  a_ (					self      :       List[str]		)       ->						Tuple:





						'''simple docstring'''







						_A					  =			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_token_classification(*__lowerCamelCase		)







		@slow
		def  a_ (					self      :       Optional[int]		)       ->						Union[str, Any]:





						'''simple docstring'''







						for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										_A					  =			EsmModel.from_pretrained(__lowerCamelCase		)
										self.assertIsNotNone(__lowerCamelCase		)







		def  a_ (					self      :       List[Any]		)       ->						str:





						'''simple docstring'''







						_A					  =			self.model_tester.prepare_config_and_inputs()[0]
						_A					  =			EsmEmbeddings(config=__lowerCamelCase		)

						_A					  =			torch.as_tensor([[12, 31, 13, model.padding_idx]]		)
						_A					  =			torch.as_tensor(
						    [
						        [
						            0 + model.padding_idx + 1,
						            1 + model.padding_idx + 1,
						            2 + model.padding_idx + 1,
						            model.padding_idx,
						        ]
						    ]		)
						_A					  =			create_position_ids_from_input_ids(__lowerCamelCase    ,   model.padding_idx		)
						self.assertEqual(position_ids.shape    ,   expected_positions.shape		)
						self.assertTrue(torch.all(torch.eq(__lowerCamelCase    ,   __lowerCamelCase		)		)		)







		def  a_ (					self      :       Dict		)       ->						int:





						'''simple docstring'''







						_A					  =			self.model_tester.prepare_config_and_inputs()[0]
						_A					  =			EsmEmbeddings(config=__lowerCamelCase		)

						_A					  =			torch.empty(2    ,   4    ,   30		)
						_A					  =			[
						    0 + embeddings.padding_idx + 1,
						    1 + embeddings.padding_idx + 1,
						    2 + embeddings.padding_idx + 1,
						    3 + embeddings.padding_idx + 1,
						]
						_A					  =			torch.as_tensor([expected_single_positions, expected_single_positions]		)
						_A					  =			embeddings.create_position_ids_from_inputs_embeds(__lowerCamelCase		)
						self.assertEqual(position_ids.shape    ,   expected_positions.shape		)
						self.assertTrue(torch.all(torch.eq(__lowerCamelCase    ,   __lowerCamelCase		)		)		)







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





						'''simple docstring'''







						pass







		@unittest.skip("Esm does not support embedding resizing"		)
		def  a_ (					self      :       Any		)       ->						int:





						'''simple docstring'''







						pass







		@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."		)
		def  a_ (					self      :       str		)       ->						Optional[Any]:





						'''simple docstring'''







						pass





@require_torch
class snake_case      (  lowerCamelCase__):







		@slow
		def  a_ (					self      :       List[Any]		)       ->						Optional[int]:





						'''simple docstring'''







						with torch.no_grad():
										_A					  =			EsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D"		)
										model.eval()
										_A					  =			torch.tensor([[0, 1, 2, 3, 4, 5]]		)
										_A					  =			model(__lowerCamelCase		)[0]

										_A					  =			33

										_A					  =			torch.Size((1, 6, vocab_size)		)
										self.assertEqual(output.shape    ,   __lowerCamelCase		)

										_A					  =			torch.tensor(
										    [[[8.9_2_1_5, -1_0.5_8_9_8, -6.4_6_7_1], [-6.3_9_6_7, -1_3.9_1_1_4, -1.1_2_1_2], [-7.7_8_1_2, -1_3.9_5_1_6, -3.7_4_0_6]]]		)
										self.assertTrue(torch.allclose(output[:, :3, :3]    ,   __lowerCamelCase    ,   atol=1E-4		)		)







		@slow
		def  a_ (					self      :       List[Any]		)       ->						Optional[int]:





						'''simple docstring'''







						with torch.no_grad():
										_A					  =			EsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D"		)
										model.eval()

										_A					  =			torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]		)
										_A					  =			model(__lowerCamelCase		)[0]
										# compare the actual values for a slice.
										_A					  =			torch.tensor(
										    [[[0.1_4_4_4, 0.5_4_1_3, 0.3_2_4_8], [0.3_0_3_4, 0.0_0_5_3, 0.3_1_0_8], [0.3_2_2_8, -0.2_4_9_9, 0.3_4_1_5]]]		)
										self.assertTrue(torch.allclose(output[:, :3, :3]    ,   __lowerCamelCase    ,   atol=1E-4		)		)



"""simple docstring"""


import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


a_       							=    False
class snake_case      (  unittest.TestCase):
		pass





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







		def  a_ (					self      :       Optional[int]		)       ->						str:





						'''simple docstring'''







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







		def  a_ (					self      :       Tuple		)       ->						Any:





						'''simple docstring'''







						_A					  =			VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion"    ,   torch_dtype=torch.floataa		)
						pipe.to(a__		)
						pipe.set_progress_bar_config(disable=a__		)

						_A					  =			load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"		)

						_A					  =			torch.manual_seed(0		)
						_A					  =			pipe.dual_guided(
						    prompt="first prompt"    ,   image=a__    ,   text_to_image_strength=0.7_5    ,   generator=a__    ,   guidance_scale=7.5    ,   num_inference_steps=2    ,   output_type="numpy"    ,   ).images

						with tempfile.TemporaryDirectory() as tmpdirname:
										pipe.save_pretrained(a__		)
										_A					  =			VersatileDiffusionPipeline.from_pretrained(a__    ,   torch_dtype=torch.floataa		)
						pipe.to(a__		)
						pipe.set_progress_bar_config(disable=a__		)

						_A					  =			generator.manual_seed(0		)
						_A					  =			pipe.dual_guided(
						    prompt="first prompt"    ,   image=a__    ,   text_to_image_strength=0.7_5    ,   generator=a__    ,   guidance_scale=7.5    ,   num_inference_steps=2    ,   output_type="numpy"    ,   ).images

						assert np.abs(image - new_image		).sum() < 1E-5, "Models don't have the same forward pass"







		def  a_ (					self      :       Optional[int]		)       ->						List[Any]:





						'''simple docstring'''







						_A					  =			VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion"    ,   torch_dtype=torch.floataa		)
						pipe.to(a__		)
						pipe.set_progress_bar_config(disable=a__		)

						_A					  =			"cyberpunk 2077"
						_A					  =			load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"		)
						_A					  =			torch.manual_seed(0		)
						_A					  =			pipe.dual_guided(
						    prompt=a__    ,   image=a__    ,   text_to_image_strength=0.7_5    ,   generator=a__    ,   guidance_scale=7.5    ,   num_inference_steps=50    ,   output_type="numpy"    ,   ).images

						_A					  =			image[0, 2_53:2_56, 2_53:2_56, -1]

						assert image.shape == (1, 5_12, 5_12, 3)
						_A					  =			np.array([0.1_4_4_8, 0.1_6_1_9, 0.1_7_4_1, 0.1_0_8_6, 0.1_1_4_7, 0.1_1_2_8, 0.1_1_9_9, 0.1_1_6_5, 0.1_0_0_1]		)

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

						_A					  =			"A painting of a squirrel eating a burger "
						_A					  =			torch.manual_seed(0		)
						_A					  =			pipe.text_to_image(
						    prompt=a__    ,   generator=a__    ,   guidance_scale=7.5    ,   num_inference_steps=50    ,   output_type="numpy"		).images

						_A					  =			image[0, 2_53:2_56, 2_53:2_56, -1]

						assert image.shape == (1, 5_12, 5_12, 3)
						_A					  =			np.array([0.3_3_6_7, 0.3_1_6_9, 0.2_6_5_6, 0.3_8_7_0, 0.4_7_9_0, 0.3_7_9_6, 0.4_0_0_9, 0.4_8_7_8, 0.4_7_7_8]		)

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

						_A					  =			pipe.image_variation(a__    ,   generator=a__    ,   output_type="numpy"		).images

						_A					  =			image[0, 2_53:2_56, 2_53:2_56, -1]

						assert image.shape == (1, 5_12, 5_12, 3)
						_A					  =			np.array([0.3_0_7_6, 0.3_1_2_3, 0.3_2_8_4, 0.3_7_8_2, 0.3_7_7_0, 0.3_8_9_4, 0.4_2_9_7, 0.4_3_3_1, 0.4_4_5_6]		)

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