



from __future__ import annotations

import unittest

from transformers import EsmConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
							import numpy
							import tensorflow as tf

							from transformers.models.esm.modeling_tf_esm import (
							    TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST,
							    TFEsmForMaskedLM,
							    TFEsmForSequenceClassification,
							    TFEsmForTokenClassification,
							    TFEsmModel,
							)

class 	lowerCamelCase_    :






						'''simple docstring'''







						def __init__(	self      :			Dict	,	__lowerCamelCase      :			List[str]	,	)      ->				Optional[int]:
									A							:					List[Any]              =						parent
									A							:					str              =						13
									A							:					Optional[int]              =						7
									A							:					int              =						True
									A							:					Any              =						True
									A							:					List[Any]              =						True
									A							:					Any              =						99
									A							:					int              =						32
									A							:					Tuple              =						2
									A							:					Union[str, Any]              =						4
									A							:					int              =						37
									A							:					Optional[int]              =						"gelu"
									A							:					Tuple              =						0.1
									A							:					Dict              =						0.1
									A							:					str              =						5_12
									A							:					Tuple              =						16
									A							:					Tuple              =						2
									A							:					str              =						0.02
									A							:					int              =						3
									A							:					Optional[int]              =						4
									A							:					Dict              =						None







						def 			SCREAMING_SNAKE_CASE__		(	self      :			int )      ->				Any:
									A							:					Any              =						ids_tensor([self.batch_size, self.seq_length]	,	self.vocab_size )

									A							:					Tuple              =						None
									if self.use_input_mask:
												A							:					List[Any]              =						random_attention_mask([self.batch_size, self.seq_length] )

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

									A							:					Optional[Any]              =						EsmConfig(
									    vocab_size=self.vocab_size	,	hidden_size=self.hidden_size	,	num_hidden_layers=self.num_hidden_layers	,	pad_token_id=1	,	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	,	)

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







						def 			SCREAMING_SNAKE_CASE__		(	self      :			int )      ->				List[Any]:
									(
									    A 
									)							:					List[str]              =						self.prepare_config_and_inputs()

									A							:					str              =						True
									A							:					str              =						floats_tensor([self.batch_size, self.seq_length, self.hidden_size] )
									A							:					Any              =						ids_tensor([self.batch_size, self.seq_length]	,	vocab_size=2 )

									return (
									    config,
									    input_ids,
									    input_mask,
									    sequence_labels,
									    token_labels,
									    choice_labels,
									    encoder_hidden_states,
									    encoder_attention_mask,
									)







						def 			SCREAMING_SNAKE_CASE__		(	self      :			List[Any]	,	__lowerCamelCase      :			str	,	__lowerCamelCase      :			str	,	__lowerCamelCase      :			Tuple	,	__lowerCamelCase      :			Tuple	,	__lowerCamelCase      :			List[Any]	,	__lowerCamelCase      :			Optional[int] )      ->				Optional[Any]:
									A							:					Tuple              =						TFEsmModel(config=__lowerCamelCase )
									A							:					List[Any]              =						{"input_ids": input_ids, "attention_mask": input_mask}
									A							:					Optional[int]              =						model(__lowerCamelCase )

									A							:					List[Any]              =						[input_ids, input_mask]
									A							:					List[Any]              =						model(__lowerCamelCase )

									A							:					Optional[Any]              =						model(__lowerCamelCase )

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







						def 			SCREAMING_SNAKE_CASE__		(	self      :			List[str]	,	__lowerCamelCase      :			List[str]	,	__lowerCamelCase      :			Dict	,	__lowerCamelCase      :			int	,	__lowerCamelCase      :			str	,	__lowerCamelCase      :			List[str]	,	__lowerCamelCase      :			Optional[Any]	,	__lowerCamelCase      :			Tuple	,	__lowerCamelCase      :			List[str]	,	)      ->				List[Any]:
									A							:					Dict              =						True

									A							:					Union[str, Any]              =						TFEsmModel(config=__lowerCamelCase )
									A							:					Optional[int]              =						{
									    "input_ids": input_ids,
									    "attention_mask": input_mask,
									    "encoder_hidden_states": encoder_hidden_states,
									    "encoder_attention_mask": encoder_attention_mask,
									}
									A							:					str              =						model(__lowerCamelCase )

									A							:					Tuple              =						[input_ids, input_mask]
									A							:					Union[str, Any]              =						model(__lowerCamelCase	,	encoder_hidden_states=__lowerCamelCase )

									# Also check the case where encoder outputs are not passed
									A							:					str              =						model(__lowerCamelCase	,	attention_mask=__lowerCamelCase )

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







						def 			SCREAMING_SNAKE_CASE__		(	self      :			str	,	__lowerCamelCase      :			Union[str, Any]	,	__lowerCamelCase      :			Optional[Any]	,	__lowerCamelCase      :			Dict	,	__lowerCamelCase      :			Union[str, Any]	,	__lowerCamelCase      :			Union[str, Any]	,	__lowerCamelCase      :			Union[str, Any] )      ->				Dict:
									A							:					Dict              =						TFEsmForMaskedLM(config=__lowerCamelCase )
									A							:					Any              =						model([input_ids, input_mask] )
									self.parent.assertEqual(result.logits.shape	,	(self.batch_size, self.seq_length, self.vocab_size) )







						def 			SCREAMING_SNAKE_CASE__		(	self      :			List[Any]	,	__lowerCamelCase      :			Dict	,	__lowerCamelCase      :			str	,	__lowerCamelCase      :			Tuple	,	__lowerCamelCase      :			Optional[int]	,	__lowerCamelCase      :			int	,	__lowerCamelCase      :			int )      ->				int:
									A							:					Any              =						self.num_labels
									A							:					Tuple              =						TFEsmForTokenClassification(config=__lowerCamelCase )
									A							:					Dict              =						{"input_ids": input_ids, "attention_mask": input_mask}
									A							:					int              =						model(__lowerCamelCase )
									self.parent.assertEqual(result.logits.shape	,	(self.batch_size, self.seq_length, self.num_labels) )







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Dict )      ->				int:
									A							:					int              =						self.prepare_config_and_inputs()
									(
									    A 
									)							:					Tuple              =						config_and_inputs
									A							:					int              =						{"input_ids": input_ids, "attention_mask": input_mask}
									return config, inputs_dict







@require_tf
class 	lowerCamelCase_    ( _A						,_A						,unittest.TestCase						):






						'''simple docstring'''
						a__   =  (
						    (
						        TFEsmModel,
						        TFEsmForMaskedLM,
						        TFEsmForSequenceClassification,
						        TFEsmForTokenClassification,
						    )
						    if is_tf_available()
						    else ()
						)
						a__   =  (
						    {
						        "feature-extraction": TFEsmModel,
						        "fill-mask": TFEsmForMaskedLM,
						        "text-classification": TFEsmForSequenceClassification,
						        "token-classification": TFEsmForTokenClassification,
						        "zero-shot": TFEsmForSequenceClassification,
						    }
						    if is_tf_available()
						    else {}
						)
						a__   =  False
						a__   =  False







						def 			SCREAMING_SNAKE_CASE__		(	self      :			int )      ->				Optional[Any]:
									A							:					Any              =						TFEsmModelTester(self )
									A							:					Optional[int]              =						ConfigTester(self	,	config_class=__lowerCamelCase	,	hidden_size=37 )







						def 			SCREAMING_SNAKE_CASE__		(	self      :			List[str] )      ->				Dict:
									self.config_tester.run_common_tests()







						def 			SCREAMING_SNAKE_CASE__		(	self      :			int )      ->				Union[str, Any]:
									A							:					str              =						self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*__lowerCamelCase )







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Optional[int] )      ->				Optional[Any]:
									A							:					int              =						self.model_tester.prepare_config_and_inputs_for_decoder()
									self.model_tester.create_and_check_model_as_decoder(*__lowerCamelCase )







						def 			SCREAMING_SNAKE_CASE__		(	self      :			int )      ->				str:
									A							:					Optional[Any]              =						self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_masked_lm(*__lowerCamelCase )







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Optional[Any] )      ->				List[Any]:
									A							:					Dict              =						self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_token_classification(*__lowerCamelCase )







						@slow
						def 			SCREAMING_SNAKE_CASE__		(	self      :			str )      ->				int:
									for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												A							:					Tuple              =						TFEsmModel.from_pretrained(__lowerCamelCase )
												self.assertIsNotNone(__lowerCamelCase )







						@unittest.skip("Protein models do not support embedding resizing." )
						def 			SCREAMING_SNAKE_CASE__		(	self      :			List[str] )      ->				Optional[int]:
									pass







						@unittest.skip("Protein models do not support embedding resizing." )
						def 			SCREAMING_SNAKE_CASE__		(	self      :			List[Any] )      ->				str:
									pass







						def 			SCREAMING_SNAKE_CASE__		(	self      :			List[Any] )      ->				str:
									A							:					int              =						self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
												A							:					Union[str, Any]              =						model_class(__lowerCamelCase )
												assert isinstance(model.get_input_embeddings()	,	tf.keras.layers.Layer )
												if model_class is TFEsmForMaskedLM:
															# Output embedding test differs from the main test because they're a matrix, not a layer
															A							:					Union[str, Any]              =						model.get_bias()
															assert isinstance(__lowerCamelCase	,	__lowerCamelCase )
															for k, v in name.items():
																		assert isinstance(__lowerCamelCase	,	tf.Variable )
												else:
															A							:					List[Any]              =						model.get_output_embeddings()
															assert x is None
															A							:					List[Any]              =						model.get_bias()
															assert name is None







@require_tf
class 	lowerCamelCase_    ( unittest.TestCase						):






						'''simple docstring'''







						@slow
						def 			SCREAMING_SNAKE_CASE__		(	self      :			Union[str, Any] )      ->				Optional[int]:
									A							:					Any              =						TFEsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D" )

									A							:					List[str]              =						tf.constant([[0, 1, 2, 3, 4, 5]] )
									A							:					Any              =						model(__lowerCamelCase )[0]
									A							:					int              =						[1, 6, 33]
									self.assertEqual(list(output.numpy().shape )	,	__lowerCamelCase )
									# compare the actual values for a slice.
									A							:					Union[str, Any]              =						tf.constant(
									    [
									        [
									            [8.921518, -10.589814, -6.4671307],
									            [-6.3967156, -13.911377, -1.1211915],
									            [-7.781247, -13.951557, -3.740592],
									        ]
									    ] )
									self.assertTrue(numpy.allclose(output[:, :3, :3].numpy()	,	expected_slice.numpy()	,	atol=1e-2 ) )







						@slow
						def 			SCREAMING_SNAKE_CASE__		(	self      :			Optional[int] )      ->				int:
									A							:					Optional[int]              =						TFEsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D" )

									A							:					int              =						tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] )
									A							:					Optional[Any]              =						model(__lowerCamelCase )[0]
									# compare the actual values for a slice.
									A							:					Dict              =						tf.constant(
									    [
									        [
									            [0.14443092, 0.54125327, 0.3247739],
									            [0.30340484, 0.00526676, 0.31077722],
									            [0.32278043, -0.24987096, 0.3414628],
									        ]
									    ] )
									self.assertTrue(numpy.allclose(output[:, :3, :3].numpy()	,	expected_slice.numpy()	,	atol=1e-4 ) )










import time
import warnings
from abc import ABC
from copy import deepcopy
from typing import Optional

import torch

from ..utils import add_start_docstrings, logging


__SCREAMING_SNAKE_CASE           =  logging.get_logger(__name__)


__SCREAMING_SNAKE_CASE           =  r"""
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
            Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax
            or scores for each vocabulary token after SoftMax.
        kwargs (`Dict[str, Any]`, *optional*):
            Additional stopping criteria specific kwargs.

    Return:
        `bool`. `False` indicates we should continue, `True` indicates we should stop.

"""

class 	lowerCamelCase_    ( _A						):






						'''simple docstring'''







						@add_start_docstrings(__lowerCamelCase )
						def __call__(	self      :			Optional[int]	,	__lowerCamelCase      :			torch.LongTensor	,	__lowerCamelCase      :			torch.FloatTensor	,	**__lowerCamelCase      :			Optional[Any] )      ->				bool:
									raise NotImplementedError("StoppingCriteria needs to be subclassed" )







class 	lowerCamelCase_    ( _A						):






						'''simple docstring'''







						def __init__(	self      :			List[str]	,	__lowerCamelCase      :			int	,	__lowerCamelCase      :			Optional[int] = None )      ->				List[Any]:
									A							:					str              =						max_length
									A							:					Optional[int]              =						max_position_embeddings







						@add_start_docstrings(__lowerCamelCase )
						def __call__(	self      :			List[str]	,	__lowerCamelCase      :			torch.LongTensor	,	__lowerCamelCase      :			torch.FloatTensor	,	**__lowerCamelCase      :			Any )      ->				bool:
									A							:					List[Any]              =						input_ids.shape[-1]
									A							:					Any              =						cur_len >= self.max_length
									if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings:
												logger.warning_once(
												    "This is a friendly reminder - the current text generation call will exceed the model's predefined "
												    F"""maximum length ({self.max_position_embeddings}). Depending on the model, you may observe """
												    "exceptions, performance degradation, or nothing at all." )
									return is_done







class 	lowerCamelCase_    ( _A						):






						'''simple docstring'''







						def __init__(	self      :			Optional[Any]	,	__lowerCamelCase      :			int	,	__lowerCamelCase      :			int )      ->				List[Any]:
									warnings.warn(
									    "The class `MaxNewTokensCriteria` is deprecated. "
									    F"""Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` """
									    "with `max_length = start_length + max_new_tokens` instead."	,	__lowerCamelCase	,	)
									A							:					str              =						start_length
									A							:					Optional[Any]              =						max_new_tokens
									A							:					Dict              =						start_length + max_new_tokens







						@add_start_docstrings(__lowerCamelCase )
						def __call__(	self      :			int	,	__lowerCamelCase      :			torch.LongTensor	,	__lowerCamelCase      :			torch.FloatTensor	,	**__lowerCamelCase      :			Tuple )      ->				bool:
									return input_ids.shape[-1] >= self.max_length







class 	lowerCamelCase_    ( _A						):






						'''simple docstring'''







						def __init__(	self      :			Optional[int]	,	__lowerCamelCase      :			float	,	__lowerCamelCase      :			Optional[float] = None )      ->				List[Any]:
									A							:					str              =						max_time
									A							:					Dict              =						time.time() if initial_timestamp is None else initial_timestamp







						@add_start_docstrings(__lowerCamelCase )
						def __call__(	self      :			Any	,	__lowerCamelCase      :			torch.LongTensor	,	__lowerCamelCase      :			torch.FloatTensor	,	**__lowerCamelCase      :			Tuple )      ->				bool:
									return time.time() - self.initial_timestamp > self.max_time







class 	lowerCamelCase_    ( _A						):






						'''simple docstring'''







						@add_start_docstrings(__lowerCamelCase )
						def __call__(	self      :			Union[str, Any]	,	__lowerCamelCase      :			torch.LongTensor	,	__lowerCamelCase      :			torch.FloatTensor	,	**__lowerCamelCase      :			int )      ->				bool:
									return any(criteria(__lowerCamelCase	,	__lowerCamelCase ) for criteria in self )







						@property
						def 			SCREAMING_SNAKE_CASE__		(	self      :			List[str] )      ->				Optional[int]:
									for stopping_criterium in self:
												if isinstance(__lowerCamelCase	,	__lowerCamelCase ):
															return stopping_criterium.max_length
												elif isinstance(__lowerCamelCase	,	__lowerCamelCase ):
															return stopping_criterium.max_length
									return None







def 	UpperCAmelCase   (						_lowerCamelCase ,    _lowerCamelCase    ):
			A							:					Optional[int]              =						stopping_criteria.max_length
			A							:					Any              =						deepcopy(_lowerCamelCase    )
			if stopping_max_length is not None and stopping_max_length != max_length:
						warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter" ,    _lowerCamelCase    )
			elif stopping_max_length is None:
						new_stopping_criteria.append(MaxLengthCriteria(max_length=_lowerCamelCase    )    )
			return new_stopping_criteria