


from typing import List, Optional, Union

import torch

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)


__A	:	Union[str, Any]     =     logging.get_logger(__name__)  # pylint: disable=invalid-name

__A	:	Any     =     '\n    Examples:\n        ```py\n        >>> import torch\n        >>> import numpy as np\n\n        >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n        >>> from transformers import pipeline\n        >>> from diffusers.utils import load_image\n\n\n        >>> def make_hint(image, depth_estimator):\n        ...     image = depth_estimator(image)["depth"]\n        ...     image = np.array(image)\n        ...     image = image[:, :, None]\n        ...     image = np.concatenate([image, image, image], axis=2)\n        ...     detected_map = torch.from_numpy(image).float() / 255.0\n        ...     hint = detected_map.permute(2, 0, 1)\n        ...     return hint\n\n\n        >>> depth_estimator = pipeline("depth-estimation")\n\n        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n        ...     "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n        ... )\n        >>> pipe_prior = pipe_prior.to("cuda")\n\n        >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n        ...     "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n        ... )\n        >>> pipe = pipe.to("cuda")\n\n\n        >>> img = load_image(\n        ...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n        ...     "/kandinsky/cat.png"\n        ... ).resize((768, 768))\n\n        >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n        >>> prompt = "A robot, 4k photo"\n        >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n        >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n        >>> image_emb, zero_image_emb = pipe_prior(\n        ...     prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n        ... ).to_tuple()\n\n        >>> images = pipe(\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=zero_image_emb,\n        ...     hint=hint,\n        ...     num_inference_steps=50,\n        ...     generator=generator,\n        ...     height=768,\n        ...     width=768,\n        ... ).images\n\n        >>> images[0].save("robot_cat.png")\n        ```\n'





def      UpperCAmelCase      (		lowerCamelCase_  :Tuple				,      lowerCamelCase_  :List[Any]				,      lowerCamelCase_  :Optional[Any]=8 ):







		'''simple docstring'''
		snake_case_		:							Union[str, Any]			       =						height // scale_factor**2
		if height % scale_factor**2 != 0:
				new_height += 1
		snake_case_		:							List[str]			       =						width // scale_factor**2
		if width % scale_factor**2 != 0:
				new_width += 1
		return new_height * scale_factor, new_width * scale_factor






class 						__UpperCamelCase	(						lowercase__							):





							def __init__(  self		:List[Any]  ,_UpperCamelCase		:UNetaDConditionModel  ,_UpperCamelCase		:DDPMScheduler  ,_UpperCamelCase		:VQModel  ,):
									super().__init__()

									self.register_modules(
									    unet=_UpperCamelCase  ,scheduler=_UpperCamelCase  ,movq=_UpperCamelCase  ,)
									snake_case_		:							Dict			       =						2 ** (len(self.movq.config.block_out_channels			) - 1)





							def 		a__   (  self		:Tuple  ,_UpperCamelCase		:List[str]  ,_UpperCamelCase		:Optional[Any]  ,_UpperCamelCase		:str  ,_UpperCamelCase		:List[Any]  ,_UpperCamelCase		:Any  ,_UpperCamelCase		:Any			):
									if latents is None:
											snake_case_		:							Optional[Any]			       =						randn_tensor(_UpperCamelCase  ,generator=_UpperCamelCase  ,device=_UpperCamelCase  ,dtype=_UpperCamelCase			)
									else:
											if latents.shape != shape:
													raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {shape}'''			)
											snake_case_		:							Optional[int]			       =						latents.to(_UpperCamelCase			)

									snake_case_		:							int			       =						latents * scheduler.init_noise_sigma
									return latents





							def 		a__   (  self		:Tuple  ,_UpperCamelCase		:Optional[int]=0			):
									if is_accelerate_available():
											from accelerate import cpu_offload
									else:
											raise ImportError("""Please install accelerate via `pip install accelerate`"""			)

									snake_case_		:							int			       =						torch.device(F'''cuda:{gpu_id}'''			)

									snake_case_		:							Union[str, Any]			       =						[
									    self.unet,
									    self.movq,
									]
									for cpu_offloaded_model in models:
											if cpu_offloaded_model is not None:
													cpu_offload(_UpperCamelCase  ,_UpperCamelCase			)





							def 		a__   (  self		:Any  ,_UpperCamelCase		:str=0			):
									if is_accelerate_available() and is_accelerate_version(""">="""  ,"""0.17.0.dev0"""			):
											from accelerate import cpu_offload_with_hook
									else:
											raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher."""			)

									snake_case_		:							Optional[Any]			       =						torch.device(F'''cuda:{gpu_id}'''			)

									if self.device.type != "cpu":
											self.to("""cpu"""  ,silence_dtype_warnings=_UpperCamelCase			)
											torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

									snake_case_		:							Union[str, Any]			       =						None
									for cpu_offloaded_model in [self.unet, self.movq]:
											snake_case_		:							Tuple			       =						cpu_offload_with_hook(_UpperCamelCase  ,_UpperCamelCase  ,prev_module_hook=_UpperCamelCase			)

									# We'll offload the last model manually.
									snake_case_		:							Optional[Any]			       =						hook





							@property
							# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
							def 		a__   (  self		:Union[str, Any]			):
									if not hasattr(self.unet  ,"""_hf_hook"""			):
											return self.device
									for module in self.unet.modules():
											if (
											    hasattr(_UpperCamelCase  ,"""_hf_hook"""			)
											    and hasattr(module._hf_hook  ,"""execution_device"""			)
											    and module._hf_hook.execution_device is not None
											):
													return torch.device(module._hf_hook.execution_device			)
									return self.device





							@torch.no_grad()
							@replace_example_docstring(_UpperCamelCase			)
							def __call__(  self		:Optional[int]  ,_UpperCamelCase		:Union[torch.FloatTensor, List[torch.FloatTensor]]  ,_UpperCamelCase		:Union[torch.FloatTensor, List[torch.FloatTensor]]  ,_UpperCamelCase		:torch.FloatTensor  ,_UpperCamelCase		:int = 5_1_2  ,_UpperCamelCase		:int = 5_1_2  ,_UpperCamelCase		:int = 1_0_0  ,_UpperCamelCase		:float = 4.0  ,_UpperCamelCase		:int = 1  ,_UpperCamelCase		:Optional[Union[torch.Generator, List[torch.Generator]]] = None  ,_UpperCamelCase		:Optional[torch.FloatTensor] = None  ,_UpperCamelCase		:Optional[str] = "pil"  ,_UpperCamelCase		:bool = True  ,):
									snake_case_		:							List[str]			       =						self._execution_device

									snake_case_		:							List[Any]			       =						guidance_scale > 1.0

									if isinstance(_UpperCamelCase  ,_UpperCamelCase			):
											snake_case_		:							Optional[Any]			       =						torch.cat(_UpperCamelCase  ,dim=0			)
									if isinstance(_UpperCamelCase  ,_UpperCamelCase			):
											snake_case_		:							List[str]			       =						torch.cat(_UpperCamelCase  ,dim=0			)
									if isinstance(_UpperCamelCase  ,_UpperCamelCase			):
											snake_case_		:							Optional[Any]			       =						torch.cat(_UpperCamelCase  ,dim=0			)

									snake_case_		:							Any			       =						image_embeds.shape[0] * num_images_per_prompt

									if do_classifier_free_guidance:
											snake_case_		:							Tuple			       =						image_embeds.repeat_interleave(_UpperCamelCase  ,dim=0			)
											snake_case_		:							str			       =						negative_image_embeds.repeat_interleave(_UpperCamelCase  ,dim=0			)
											snake_case_		:							Optional[Any]			       =						hint.repeat_interleave(_UpperCamelCase  ,dim=0			)

									snake_case_		:							Any			       =						torch.cat([negative_image_embeds, image_embeds]  ,dim=0			).to(dtype=self.unet.dtype  ,device=_UpperCamelCase			)
									snake_case_		:							int			       =						torch.cat([hint, hint]  ,dim=0			).to(dtype=self.unet.dtype  ,device=_UpperCamelCase			)
									self.scheduler.set_timesteps(_UpperCamelCase  ,device=_UpperCamelCase			)
									snake_case_		:							List[str]			       =						self.scheduler.timesteps

									snake_case_		:							List[Any]			       =						self.movq.config.latent_channels

									snake_case_		:							List[str]			       =						downscale_height_and_width(_UpperCamelCase  ,_UpperCamelCase  ,self.movq_scale_factor			)

									# create initial latent
									snake_case_		:							Any			       =						self.prepare_latents(
									    (batch_size, num_channels_latents, height, width)  ,image_embeds.dtype  ,_UpperCamelCase  ,_UpperCamelCase  ,_UpperCamelCase  ,self.scheduler  ,)

									for i, t in enumerate(self.progress_bar(_UpperCamelCase			)			):
											# expand the latents if we are doing classifier free guidance
											snake_case_		:							str			       =						torch.cat([latents] * 2			) if do_classifier_free_guidance else latents

											snake_case_		:							List[str]			       =						{"""image_embeds""": image_embeds, """hint""": hint}
											snake_case_		:							Tuple			       =						self.unet(
											    sample=_UpperCamelCase  ,timestep=_UpperCamelCase  ,encoder_hidden_states=_UpperCamelCase  ,added_cond_kwargs=_UpperCamelCase  ,return_dict=_UpperCamelCase  ,)[0]

											if do_classifier_free_guidance:
													snake_case_		:							Tuple			       =						noise_pred.split(latents.shape[1]  ,dim=1			)
													snake_case_		:							str			       =						noise_pred.chunk(2			)
													snake_case_		:							Optional[Any]			       =						variance_pred.chunk(2			)
													snake_case_		:							int			       =						noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
													snake_case_		:							Tuple			       =						torch.cat([noise_pred, variance_pred_text]  ,dim=1			)

											if not (
											    hasattr(self.scheduler.config  ,"""variance_type"""			)
											    and self.scheduler.config.variance_type in ["learned", "learned_range"]
											):
													snake_case_		:							Dict			       =						noise_pred.split(latents.shape[1]  ,dim=1			)

											# compute the previous noisy sample x_t -> x_t-1
											snake_case_		:							Optional[Any]			       =						self.scheduler.step(
											    _UpperCamelCase  ,_UpperCamelCase  ,_UpperCamelCase  ,generator=_UpperCamelCase  ,)[0]
									# post-processing
									snake_case_		:							Any			       =						self.movq.decode(_UpperCamelCase  ,force_not_quantize=_UpperCamelCase			)["""sample"""]

									if output_type not in ["pt", "np", "pil"]:
											raise ValueError(F'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}'''			)

									if output_type in ["np", "pil"]:
											snake_case_		:							Tuple			       =						image * 0.5 + 0.5
											snake_case_		:							Optional[int]			       =						image.clamp(0  ,1			)
											snake_case_		:							Optional[Any]			       =						image.cpu().permute(0  ,2  ,3  ,1			).float().numpy()

									if output_type == "pil":
											snake_case_		:							Any			       =						self.numpy_to_pil(_UpperCamelCase			)

									if not return_dict:
											return (image,)

									return ImagePipelineOutput(images=_UpperCamelCase			)



'''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 						__UpperCamelCase	:





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





							def 		a__   (  self		:str			):
									snake_case_		:							Dict			       =						ids_tensor([self.batch_size, self.seq_length]  ,self.vocab_size			)

									snake_case_		:							str			       =						None
									if self.use_input_mask:
											snake_case_		:							Optional[int]			       =						random_attention_mask([self.batch_size, self.seq_length]			)

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

									snake_case_		:							Dict			       =						self.get_config()

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





							def 		a__   (  self		:Optional[Any]			):
									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		:str  ,_UpperCamelCase		:List[Any]  ,_UpperCamelCase		:List[str]  ,_UpperCamelCase		:Any  ,_UpperCamelCase		:Optional[int]  ,_UpperCamelCase		:List[Any]  ,_UpperCamelCase		:Optional[int]			):
									snake_case_		:							Union[str, Any]			       =						EsmModel(config=_UpperCamelCase			)
									model.to(_UpperCamelCase			)
									model.eval()
									snake_case_		:							int			       =						model(_UpperCamelCase  ,attention_mask=_UpperCamelCase			)
									snake_case_		:							str			       =						model(_UpperCamelCase			)
									snake_case_		:							Optional[int]			       =						model(_UpperCamelCase			)

									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		:Any  ,_UpperCamelCase		:Optional[Any]  ,_UpperCamelCase		:Optional[Any]  ,_UpperCamelCase		:Any  ,_UpperCamelCase		:Dict  ,_UpperCamelCase		:Union[str, Any]  ,_UpperCamelCase		:Optional[int]			):
									snake_case_		:							str			       =						EsmForMaskedLM(config=_UpperCamelCase			)
									model.to(_UpperCamelCase			)
									model.eval()
									snake_case_		:							Dict			       =						model(_UpperCamelCase  ,attention_mask=_UpperCamelCase  ,labels=_UpperCamelCase			)
									self.parent.assertEqual(result.logits.shape  ,(self.batch_size, self.seq_length, self.vocab_size)			)





							def 		a__   (  self		:Optional[int]  ,_UpperCamelCase		:Optional[Any]  ,_UpperCamelCase		:List[str]  ,_UpperCamelCase		:Union[str, Any]  ,_UpperCamelCase		:Union[str, Any]  ,_UpperCamelCase		:Union[str, Any]  ,_UpperCamelCase		:Any			):
									snake_case_		:							List[Any]			       =						self.num_labels
									snake_case_		:							int			       =						EsmForTokenClassification(config=_UpperCamelCase			)
									model.to(_UpperCamelCase			)
									model.eval()
									snake_case_		:							int			       =						model(_UpperCamelCase  ,attention_mask=_UpperCamelCase  ,labels=_UpperCamelCase			)
									self.parent.assertEqual(result.logits.shape  ,(self.batch_size, self.seq_length, self.num_labels)			)





							def 		a__   (  self		:Union[str, Any]			):
									snake_case_		:							Dict			       =						self.prepare_config_and_inputs()
									(
									    (
									    snake_case_
									)       ,      (
									    snake_case_
									)       ,      (
									    snake_case_
									)       ,      (
									    snake_case_
									)       ,      (
									    snake_case_
									)       ,      (
									    snake_case_
									)       ,      
									)		:							Optional[int]			       =						config_and_inputs
									snake_case_		:							List[str]			       =						{"""input_ids""": input_ids, """attention_mask""": input_mask}
									return config, inputs_dict





@require_torch
class 						__UpperCamelCase	(						lowercase__						,  lowercase__						,  unittest.TestCase							):
							lowercase			:		Optional[int]   		=  False

							lowercase			:		List[str]   		=  (
							    (
							        EsmForMaskedLM,
							        EsmModel,
							        EsmForSequenceClassification,
							        EsmForTokenClassification,
							    )
							    if is_torch_available()
							    else ()
							)
							lowercase			:		int   		=  ()
							lowercase			:		List[str]   		=  (
							    {
							        'feature-extraction': EsmModel,
							        'fill-mask': EsmForMaskedLM,
							        'text-classification': EsmForSequenceClassification,
							        'token-classification': EsmForTokenClassification,
							        'zero-shot': EsmForSequenceClassification,
							    }
							    if is_torch_available()
							    else {}
							)
							lowercase			:		str   		=  True





							def 		a__   (  self		:Any			):
									snake_case_		:							Any			       =						EsmModelTester(self			)
									snake_case_		:							str			       =						ConfigTester(self  ,config_class=_UpperCamelCase  ,hidden_size=3_7			)





							def 		a__   (  self		:Optional[Any]			):
									self.config_tester.run_common_tests()





							def 		a__   (  self		:Optional[Any]			):
									snake_case_		:							str			       =						self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_UpperCamelCase			)





							def 		a__   (  self		:Dict			):
									snake_case_		:							Dict			       =						self.model_tester.prepare_config_and_inputs()
									for type in ["absolute", "relative_key", "relative_key_query"]:
											snake_case_		:							int			       =						type
											self.model_tester.create_and_check_model(*_UpperCamelCase			)





							def 		a__   (  self		:Dict			):
									snake_case_		:							str			       =						self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_masked_lm(*_UpperCamelCase			)





							def 		a__   (  self		:List[str]			):
									snake_case_		:							List[str]			       =						self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_token_classification(*_UpperCamelCase			)





							@slow
							def 		a__   (  self		:Union[str, Any]			):
									for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											snake_case_		:							int			       =						EsmModel.from_pretrained(_UpperCamelCase			)
											self.assertIsNotNone(_UpperCamelCase			)





							def 		a__   (  self		:Tuple			):
									snake_case_		:							Dict			       =						self.model_tester.prepare_config_and_inputs()[0]
									snake_case_		:							Optional[int]			       =						EsmEmbeddings(config=_UpperCamelCase			)

									snake_case_		:							List[Any]			       =						torch.as_tensor([[1_2, 3_1, 1_3, model.padding_idx]]			)
									snake_case_		:							Union[str, Any]			       =						torch.as_tensor(
									    [
									        [
									            0 + model.padding_idx + 1,
									            1 + model.padding_idx + 1,
									            2 + model.padding_idx + 1,
									            model.padding_idx,
									        ]
									    ]			)
									snake_case_		:							Optional[Any]			       =						create_position_ids_from_input_ids(_UpperCamelCase  ,model.padding_idx			)
									self.assertEqual(position_ids.shape  ,expected_positions.shape			)
									self.assertTrue(torch.all(torch.eq(_UpperCamelCase  ,_UpperCamelCase			)			)			)





							def 		a__   (  self		:List[Any]			):
									snake_case_		:							Union[str, Any]			       =						self.model_tester.prepare_config_and_inputs()[0]
									snake_case_		:							List[Any]			       =						EsmEmbeddings(config=_UpperCamelCase			)

									snake_case_		:							Dict			       =						torch.empty(2  ,4  ,3_0			)
									snake_case_		:							List[Any]			       =						[
									    0 + embeddings.padding_idx + 1,
									    1 + embeddings.padding_idx + 1,
									    2 + embeddings.padding_idx + 1,
									    3 + embeddings.padding_idx + 1,
									]
									snake_case_		:							Any			       =						torch.as_tensor([expected_single_positions, expected_single_positions]			)
									snake_case_		:							str			       =						embeddings.create_position_ids_from_inputs_embeds(_UpperCamelCase			)
									self.assertEqual(position_ids.shape  ,expected_positions.shape			)
									self.assertTrue(torch.all(torch.eq(_UpperCamelCase  ,_UpperCamelCase			)			)			)





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





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





							@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""			)
							def 		a__   (  self		:Optional[int]			):
									pass





@require_torch
class 						__UpperCamelCase	(						lowercase__							):





							@slow
							def 		a__   (  self		:Any			):
									with torch.no_grad():
											snake_case_		:							Optional[Any]			       =						EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D"""			)
											model.eval()
											snake_case_		:							List[Any]			       =						torch.tensor([[0, 1, 2, 3, 4, 5]]			)
											snake_case_		:							Dict			       =						model(_UpperCamelCase			)[0]

											snake_case_		:							Optional[int]			       =						3_3

											snake_case_		:							List[Any]			       =						torch.Size((1, 6, vocab_size)			)
											self.assertEqual(output.shape  ,_UpperCamelCase			)

											snake_case_		:							Union[str, Any]			       =						torch.tensor(
											    [[[8.92_15, -10.58_98, -6.46_71], [-6.39_67, -13.91_14, -1.12_12], [-7.78_12, -13.95_16, -3.74_06]]]			)
											self.assertTrue(torch.allclose(output[:, :3, :3]  ,_UpperCamelCase  ,atol=1E-4			)			)





							@slow
							def 		a__   (  self		:List[Any]			):
									with torch.no_grad():
											snake_case_		:							List[Any]			       =						EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D"""			)
											model.eval()

											snake_case_		:							str			       =						torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]]			)
											snake_case_		:							Optional[Any]			       =						model(_UpperCamelCase			)[0]
											# compare the actual values for a slice.
											snake_case_		:							List[str]			       =						torch.tensor(
											    [[[0.14_44, 0.54_13, 0.32_48], [0.30_34, 0.00_53, 0.31_08], [0.32_28, -0.24_99, 0.34_15]]]			)
											self.assertTrue(torch.allclose(output[:, :3, :3]  ,_UpperCamelCase  ,atol=1E-4			)			)