





import copy
import tempfile
import unittest

from transformers import MaMaaaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from transformers.utils import cached_property

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer
					from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder







def        __lowerCamelCase (							__a       :Union[str, Any]   ,					__a       :Tuple   ,					__a       :Dict   ,					__a       :Any=None   ,					__a       :List[Any]=None   ,					__a       :Any=None   ,					__a       :Dict=None   ,					__a       :Union[str, Any]=None   ,					)		->    Dict:






		"""simple docstring"""

		if attention_mask is None:
				A__  				=       input_ids.ne(config.pad_token_id   )
		if decoder_attention_mask is None:
				A__  				=       decoder_input_ids.ne(config.pad_token_id   )
		if head_mask is None:
				A__  				=       torch.ones(config.encoder_layers   ,					config.encoder_attention_heads   ,					device=a__   )
		if decoder_head_mask is None:
				A__  				=       torch.ones(config.decoder_layers   ,					config.decoder_attention_heads   ,					device=a__   )
		if cross_attn_head_mask is None:
				A__  				=       torch.ones(config.decoder_layers   ,					config.decoder_attention_heads   ,					device=a__   )
		return {
		    "input_ids": input_ids,
		    "decoder_input_ids": decoder_input_ids,
		    "attention_mask": attention_mask,
		    "decoder_attention_mask": attention_mask,
		    "head_mask": head_mask,
		    "decoder_head_mask": decoder_head_mask,
		    "cross_attn_head_mask": cross_attn_head_mask,
		}


class   A      :
			'''simple docstring'''




			def __init__(      self       :   List[Any]							,     __lowerCAmelCase       :   List[Any]							,     __lowerCAmelCase       :   Dict=13							,     __lowerCAmelCase       :   str=7							,     __lowerCAmelCase       :   str=True							,     __lowerCAmelCase       :   List[str]=False							,     __lowerCAmelCase       :   List[Any]=99							,     __lowerCAmelCase       :   List[str]=16							,     __lowerCAmelCase       :   int=2							,     __lowerCAmelCase       :   Any=4							,     __lowerCAmelCase       :   Tuple=4							,     __lowerCAmelCase       :   Dict="relu"							,     __lowerCAmelCase       :   Any=0.1							,     __lowerCAmelCase       :   Dict=0.1							,     __lowerCAmelCase       :   Union[str, Any]=0.0							,     __lowerCAmelCase       :   List[Any]=0.0							,     __lowerCAmelCase       :   Any=20							,     __lowerCAmelCase       :   int=2							,     __lowerCAmelCase       :   Optional[Any]=1							,     __lowerCAmelCase       :   int=0							,     )     ->     Optional[Any]:







					"""simple docstring"""






					A__  				=       parent
					A__  				=       batch_size
					A__  				=       seq_length
					A__  				=       is_training
					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__  				=       encoder_layerdrop
					A__  				=       decoder_layerdrop
					A__  				=       max_position_embeddings
					A__  				=       eos_token_id
					A__  				=       pad_token_id
					A__  				=       bos_token_id






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







					"""simple docstring"""






					A__  				=       ids_tensor([self.batch_size, self.seq_length]							,     self.vocab_size       )
					A__  				=       self.eos_token_id  # Eos Token
					A__  				=       ids_tensor([self.batch_size, self.seq_length]							,     self.vocab_size       )

					# we need to clamp the input ids here to avoid having pad token in between
					# this is because for M2M100 the position_ids are prepared such that
					# all pad tokens have pos id = 2 and rest are between 2..seq_length
					# and the seq_length here is seq_length - num_pad_tokens
					# but when using past, there is no way of knowing if the past input ids had
					# pad tokens in them, which results in incorrect seq_lenth and which in turn results in
					# position_ids being off by num_pad_tokens in past input
					A__  				=       input_ids.clamp(self.pad_token_id + 1       )
					A__  				=       decoder_input_ids.clamp(self.pad_token_id + 1       )

					A__  				=       self.get_config()
					A__  				=       prepare_mam_aaa_inputs_dict(_lowerCamelCase							,     _lowerCamelCase							,     _lowerCamelCase       )
					return config, inputs_dict






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







					"""simple docstring"""






					return MaMaaaConfig(
					    vocab_size=self.vocab_size							,     d_model=self.hidden_size							,     encoder_layers=self.num_hidden_layers							,     decoder_layers=self.num_hidden_layers							,     encoder_attention_heads=self.num_attention_heads							,     decoder_attention_heads=self.num_attention_heads							,     encoder_ffn_dim=self.intermediate_size							,     decoder_ffn_dim=self.intermediate_size							,     dropout=self.hidden_dropout_prob							,     attention_dropout=self.attention_probs_dropout_prob							,     encoder_layerdrop=self.encoder_layerdrop							,     decoder_layerdrop=self.decoder_layerdrop							,     max_position_embeddings=self.max_position_embeddings							,     eos_token_id=self.eos_token_id							,     bos_token_id=self.bos_token_id							,     pad_token_id=self.pad_token_id							,     )






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







					"""simple docstring"""






					A__  				=       self.prepare_config_and_inputs()
					return config, inputs_dict






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







					"""simple docstring"""






					A__  				=       MaMaaaModel(config=_lowerCamelCase       ).get_decoder().to(_lowerCamelCase       ).eval()
					A__  				=       inputs_dict['''input_ids''']
					A__  				=       inputs_dict['''attention_mask''']
					A__  				=       inputs_dict['''head_mask''']

					# first forward pass
					A__  				=       model(_lowerCamelCase							,     attention_mask=_lowerCamelCase							,     head_mask=_lowerCamelCase							,     use_cache=_lowerCamelCase       )

					A__  				=       outputs.to_tuple()

					# create hypothetical multiple next token and extent to next_input_ids
					A__  				=       ids_tensor((self.batch_size, 3)							,     config.vocab_size       )
					A__  				=       ids_tensor((self.batch_size, 3)							,     2       )

					# append to next input_ids and
					A__  				=       torch.cat([input_ids, next_tokens]							,     dim=-1       )
					A__  				=       torch.cat([attention_mask, next_attn_mask]							,     dim=-1       )

					A__  				=       model(_lowerCamelCase							,     attention_mask=_lowerCamelCase       )['''last_hidden_state''']
					A__  				=       model(_lowerCamelCase							,     attention_mask=_lowerCamelCase							,     past_key_values=_lowerCamelCase       )[
					    '''last_hidden_state'''
					]

					# select random slice
					A__  				=       ids_tensor((1,)							,     output_from_past.shape[-1]       ).item()
					A__  				=       output_from_no_past[:, -3:, random_slice_idx].detach()
					A__  				=       output_from_past[:, :, random_slice_idx].detach()

					self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]       )

					# test that outputs are equal for slice
					self.parent.assertTrue(torch.allclose(_lowerCamelCase							,     _lowerCamelCase							,     atol=1e-2       )       )







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







					"""simple docstring"""






					A__  				=       MaMaaaModel(config=_lowerCamelCase       ).to(_lowerCamelCase       ).eval()
					A__  				=       model(**_lowerCamelCase       )

					A__  				=       outputs.encoder_last_hidden_state
					A__  				=       outputs.last_hidden_state

					with tempfile.TemporaryDirectory() as tmpdirname:
							A__  				=       model.get_encoder()
							encoder.save_pretrained(_lowerCamelCase       )
							A__  				=       MaMaaaEncoder.from_pretrained(_lowerCamelCase       ).to(_lowerCamelCase       )

					A__  				=       encoder(inputs_dict["""input_ids"""]							,     attention_mask=inputs_dict["""attention_mask"""]       )[
					    0
					]

					self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3       )

					with tempfile.TemporaryDirectory() as tmpdirname:
							A__  				=       model.get_decoder()
							decoder.save_pretrained(_lowerCamelCase       )
							A__  				=       MaMaaaDecoder.from_pretrained(_lowerCamelCase       ).to(_lowerCamelCase       )

					A__  				=       decoder(
					    input_ids=inputs_dict["""decoder_input_ids"""]							,     attention_mask=inputs_dict["""decoder_attention_mask"""]							,     encoder_hidden_states=_lowerCamelCase							,     encoder_attention_mask=inputs_dict["""attention_mask"""]							,     )[0]

					self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3       )


@require_torch
class   A      (a__       ,					a__       ,					a__       ,					unittest.TestCase							):
			'''simple docstring'''




			__lowerCamelCase     :	Union[str, Any]          =   (
			    (
			        MaMaaaModel,
			        MaMaaaForConditionalGeneration,
			    )
			    if is_torch_available()
			    else ()
			)
			__lowerCamelCase     :	Any          =   (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
			__lowerCamelCase     :	Optional[int]          =   (
			    {
			        'conversational': MaMaaaForConditionalGeneration,
			        'feature-extraction': MaMaaaModel,
			        'summarization': MaMaaaForConditionalGeneration,
			        'text2text-generation': MaMaaaForConditionalGeneration,
			        'translation': MaMaaaForConditionalGeneration,
			    }
			    if is_torch_available()
			    else {}
			)
			__lowerCamelCase     :	str          =   True
			__lowerCamelCase     :	int          =   True
			__lowerCamelCase     :	Any          =   False
			__lowerCamelCase     :	int          =   False






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







					"""simple docstring"""






					if pipeline_test_casse_name == "TranslationPipelineTests":
							# Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`.
							# `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer.
							return True

					return False






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







					"""simple docstring"""






					A__  				=       MaMaaaModelTester(self       )
					A__  				=       ConfigTester(self							,     config_class=_lowerCamelCase       )






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







					"""simple docstring"""






					self.config_tester.run_common_tests()






			def        a_	(      self       :   Tuple       )     ->     str:







					"""simple docstring"""






					A__  				=       self.model_tester.prepare_config_and_inputs()
					for model_class in self.all_model_classes:
							A__  				=       model_class(_lowerCamelCase       )

							with tempfile.TemporaryDirectory() as tmpdirname:
									model.save_pretrained(_lowerCamelCase       )
									A__  				=       model_class.from_pretrained(_lowerCamelCase							,     output_loading_info=_lowerCamelCase       )
							self.assertEqual(info["""missing_keys"""]							,     []       )






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







					"""simple docstring"""






					A__  				=       self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_decoder_model_past_large_inputs(*_lowerCamelCase       )






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







					"""simple docstring"""






					A__  				=       self.model_tester.prepare_config_and_inputs_for_common()
					self.model_tester.check_encoder_decoder_model_standalone(*_lowerCamelCase       )






			def        a_	(      self       :   Any       )     ->     Any:







					"""simple docstring"""






					A__  				=       self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
							A__  				=       model_class(_lowerCamelCase       )
							model.to(_lowerCamelCase       )
							model.eval()

							A__  				=       copy.deepcopy(self._prepare_for_class(_lowerCamelCase							,     _lowerCamelCase       )       )

							if not self.is_encoder_decoder:
									A__  				=       inputs['''input_ids''']
									del inputs["input_ids"]
							else:
									A__  				=       inputs['''input_ids''']
									A__  				=       inputs.get("""decoder_input_ids"""							,     _lowerCamelCase       )
									del inputs["input_ids"]
									inputs.pop("""decoder_input_ids"""							,     _lowerCamelCase       )

							A__  				=       model.get_input_embeddings()
							if not self.is_encoder_decoder:
									A__  				=       wte(_lowerCamelCase       )
							else:
									A__  				=       wte(_lowerCamelCase       )
									A__  				=       wte(_lowerCamelCase       )

							with torch.no_grad():
									model(**_lowerCamelCase       )[0]







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







					"""simple docstring"""






					A__  				=       self.model_tester.prepare_config_and_inputs()
					A__  				=       input_dict['''input_ids''']
					A__  				=       input_ids.ne(1       ).to(_lowerCamelCase       )
					A__  				=       MaMaaaForConditionalGeneration(_lowerCamelCase       ).eval().to(_lowerCamelCase       )
					if torch_device == "cuda":
							model.half()
					model.generate(_lowerCamelCase							,     attention_mask=_lowerCamelCase       )
					model.generate(num_beams=4							,     do_sample=_lowerCamelCase							,     early_stopping=_lowerCamelCase							,     num_return_sequences=3       )







def        __lowerCamelCase (							__a       :Optional[int]   )		->    Optional[Any]:






		"""simple docstring"""

		return torch.tensor(a__   ,					dtype=torch.long   ,					device=a__   )


A   : Optional[int]			=				1e-4






@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class   A      (unittest.TestCase							):
			'''simple docstring'''




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







					"""simple docstring"""






					return MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M"""       )






			def        a_	(      self       :   Tuple       )     ->     Dict:







					"""simple docstring"""






					A__  				=       MaMaaaModel.from_pretrained("""facebook/m2m100_418M"""       ).to(_lowerCamelCase       )
					A__  				=       _long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]]       )
					A__  				=       _long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]]       )
					A__  				=       prepare_mam_aaa_inputs_dict(model.config							,     _lowerCamelCase							,     _lowerCamelCase       )
					with torch.no_grad():
							A__  				=       model(**_lowerCamelCase       )[0]
					A__  				=       torch.Size((1, 11, 10_24)       )
					self.assertEqual(output.shape							,     _lowerCamelCase       )
					# change to expected output here
					A__  				=       torch.tensor(
					    [[-0.7_7_8_0, -0.1_6_7_6, 0.1_0_3_8], [-6.7_5_5_6, -1.3_9_9_2, 0.0_5_6_7], [-7.5_3_8_3, -0.5_9_2_0, -0.2_7_7_9]]							,     device=_lowerCamelCase       )
					self.assertTrue(torch.allclose(output[:, :3, :3]							,     _lowerCamelCase							,     atol=_lowerCamelCase       )       )






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







					"""simple docstring"""






					A__  				=       MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M"""       ).to(_lowerCamelCase       )

					# change to intended input
					A__  				=       _long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]]       )
					A__  				=       _long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]]       )
					A__  				=       prepare_mam_aaa_inputs_dict(model.config							,     _lowerCamelCase							,     _lowerCamelCase       )
					with torch.no_grad():
							A__  				=       model(**_lowerCamelCase       )[0]
					A__  				=       torch.Size((1, 11, model.config.vocab_size)       )
					self.assertEqual(output.shape							,     _lowerCamelCase       )
					# change to expected output here
					A__  				=       torch.tensor(
					    [[-1.0_4_4_8, -1.0_4_1_1, 3.7_9_9_2], [-3.2_1_9_1, -3.2_3_8_6, -1.3_4_5_1], [-3.6_2_1_0, -3.5_9_9_3, 0.4_9_2_5]]							,     device=_lowerCamelCase       )
					self.assertTrue(torch.allclose(output[:, :3, :3]							,     _lowerCamelCase							,     atol=_lowerCamelCase       )       )







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







					"""simple docstring"""






					A__  				=       MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M"""       ).to(_lowerCamelCase       )
					A__  				=       MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M"""							,     src_lang="""fr"""							,     tgt_lang="""en"""       )

					A__  				=       [
					    '''L\'affaire NSA souligne l\'absence totale de débat sur le renseignement''',
					    '''Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.''',
					    '''Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent'''
					    ''' Fabius convoque l\'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de'''
					    ''' l\'ampleur de la surveillance américaine sur l\'ensemble des communications en France.''',
					]

					# The below article tests that we don't add any hypotheses outside of the top n_beams
					A__  				=       tokenizer(_lowerCamelCase							,     padding=_lowerCamelCase							,     return_tensors="""pt"""       )

					A__  				=       model.generate(
					    input_ids=dct["""input_ids"""].to(_lowerCamelCase       )							,     attention_mask=dct["""attention_mask"""].to(_lowerCamelCase       )							,     num_beams=5							,     forced_bos_token_id=tokenizer.get_lang_id("""en"""       )							,     )

					A__  				=       [
					    '''The NSA case highlights the total absence of intelligence debate''',
					    '''I think there are two levels of response from the French government.''',
					    '''When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S.'''
					    ''' Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all'''
					    ''' communications in France.''',
					]

					A__  				=       tokenizer.batch_decode(
					    hypotheses_batch.tolist()							,     clean_up_tokenization_spaces=_lowerCamelCase							,     skip_special_tokens=_lowerCamelCase       )
					assert generated == expected_en










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   A      :
			'''simple docstring'''




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







					"""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       :   Optional[int]       )     ->     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       :   str							,     __lowerCAmelCase       :   List[Any]							,     __lowerCAmelCase       :   int							,     __lowerCAmelCase       :   int							,     __lowerCAmelCase       :   int							,     __lowerCAmelCase       :   Any							,     __lowerCAmelCase       :   Optional[int]       )     ->     str:







					"""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       :   List[Any]							,     __lowerCAmelCase       :   List[str]							,     __lowerCAmelCase       :   List[str]							,     __lowerCAmelCase       :   Tuple							,     __lowerCAmelCase       :   Optional[int]							,     __lowerCAmelCase       :   Union[str, Any]							,     __lowerCAmelCase       :   Any       )     ->     str:







					"""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]							,     __lowerCAmelCase       :   List[Any]							,     __lowerCAmelCase       :   int							,     __lowerCAmelCase       :   Optional[Any]							,     __lowerCAmelCase       :   str							,     __lowerCAmelCase       :   str							,     __lowerCAmelCase       :   List[str]       )     ->     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       :   Any       )     ->     Dict:







					"""simple docstring"""






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


@require_torch
class   A      (SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE       ,					unittest.TestCase   ):
			'''simple docstring'''




			__lowerCamelCase     :	List[str]          =   False

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






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







					"""simple docstring"""






					A__  				=       EsmModelTester(self       )
					A__  				=       ConfigTester(self							,     config_class=__lowerCAmelCase							,     hidden_size=37       )






			def        a_	(      self       :   Any       )     ->     str:







					"""simple docstring"""






					self.config_tester.run_common_tests()






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







					"""simple docstring"""






					A__  				=       self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*__lowerCAmelCase       )






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







					"""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       :   Optional[Any]       )     ->     Optional[Any]:







					"""simple docstring"""






					A__  				=       self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_masked_lm(*__lowerCAmelCase       )






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







					"""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]       )     ->     int:







					"""simple docstring"""






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






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







					"""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       :   List[Any]       )     ->     str:







					"""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       :   Dict       )     ->     Tuple:







					"""simple docstring"""






					pass






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







					"""simple docstring"""






					pass







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







					"""simple docstring"""






					pass


@require_torch
class   A      (SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''




			@slow
			def        a_	(      self       :   int       )     ->     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[str]       )     ->     Tuple:







					"""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       )       )



