





'''simple docstring'''


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 				a_       :





     def __init__(			self		: Optional[Any]     ,				lowercase		: str     ,				):





        """simple docstring"""




        lowercase_      :str         =			parent
        lowercase_      :Optional[int]         =			13
        lowercase_      :List[Any]         =			7
        lowercase_      :int         =			True
        lowercase_      :str         =			True
        lowercase_      :str         =			True
        lowercase_      :str         =			99
        lowercase_      :str         =			32
        lowercase_      :Any         =			2
        lowercase_      :List[Any]         =			4
        lowercase_      :int         =			37
        lowercase_      :Tuple         =			"gelu"
        lowercase_      :Optional[int]         =			0.1
        lowercase_      :Optional[int]         =			0.1
        lowercase_      :str         =			512
        lowercase_      :Any         =			16
        lowercase_      :int         =			2
        lowercase_      :int         =			0.02
        lowercase_      :Dict         =			3
        lowercase_      :Optional[Any]         =			4
        lowercase_      :List[Any]         =			None





     def 							lowercase__				(			self		: Any						):





        """simple docstring"""




        lowercase_      :int         =			ids_tensor([self.batch_size, self.seq_length]     ,				self.vocab_size						)

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

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

        lowercase_      :Dict         =			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 							lowercase__				(			self		: List[Any]						):





        """simple docstring"""




        (
            (
            lowercase_
        )      ,							(
            lowercase_
        )      ,							(
            lowercase_
        )      ,							(
            lowercase_
        )      ,							(
            lowercase_
        )      ,							(
            lowercase_
        )      ,							
        )      :List[Any]         =			self.prepare_config_and_inputs()

        lowercase_      :Optional[Any]         =			True
        lowercase_      :List[str]         =			floats_tensor([self.batch_size, self.seq_length, self.hidden_size]						)
        lowercase_      :Union[str, 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 							lowercase__				(			self		: Any     ,				lowercase		: Optional[int]     ,				lowercase		: Optional[int]     ,				lowercase		: Union[str, Any]     ,				lowercase		: Any     ,				lowercase		: int     ,				lowercase		: List[Any]						):





        """simple docstring"""




        lowercase_      :str         =			TFEsmModel(config=lowercase						)
        lowercase_      :str         =			{"input_ids": input_ids, "attention_mask": input_mask}
        lowercase_      :Optional[int]         =			model(lowercase						)

        lowercase_      :List[str]         =			[input_ids, input_mask]
        lowercase_      :Any         =			model(lowercase						)

        lowercase_      :List[str]         =			model(lowercase						)

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





     def 							lowercase__				(			self		: List[str]     ,				lowercase		: Union[str, Any]     ,				lowercase		: List[str]     ,				lowercase		: List[str]     ,				lowercase		: int     ,				lowercase		: Optional[Any]     ,				lowercase		: Any     ,				lowercase		: Optional[int]     ,				lowercase		: Dict     ,				):





        """simple docstring"""




        lowercase_      :Union[str, Any]         =			True

        lowercase_      :Any         =			TFEsmModel(config=lowercase						)
        lowercase_      :Tuple         =			{
            "input_ids": input_ids,
            "attention_mask": input_mask,
            "encoder_hidden_states": encoder_hidden_states,
            "encoder_attention_mask": encoder_attention_mask,
        }
        lowercase_      :Tuple         =			model(lowercase						)

        lowercase_      :Tuple         =			[input_ids, input_mask]
        lowercase_      :int         =			model(lowercase     ,				encoder_hidden_states=lowercase						)

        # Also check the case where encoder outputs are not passed
        lowercase_      :Any         =			model(lowercase     ,				attention_mask=lowercase						)

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





     def 							lowercase__				(			self		: Dict     ,				lowercase		: List[str]     ,				lowercase		: Optional[Any]     ,				lowercase		: Any     ,				lowercase		: Optional[Any]     ,				lowercase		: Any     ,				lowercase		: Any						):





        """simple docstring"""




        lowercase_      :Dict         =			TFEsmForMaskedLM(config=lowercase						)
        lowercase_      :List[str]         =			model([input_ids, input_mask]						)
        self.parent.assertEqual(result.logits.shape     ,				(self.batch_size, self.seq_length, self.vocab_size)						)





     def 							lowercase__				(			self		: Dict     ,				lowercase		: str     ,				lowercase		: Optional[int]     ,				lowercase		: Any     ,				lowercase		: str     ,				lowercase		: str     ,				lowercase		: Optional[int]						):





        """simple docstring"""




        lowercase_      :List[Any]         =			self.num_labels
        lowercase_      :Union[str, Any]         =			TFEsmForTokenClassification(config=lowercase						)
        lowercase_      :List[Any]         =			{"input_ids": input_ids, "attention_mask": input_mask}
        lowercase_      :Optional[Any]         =			model(lowercase						)
        self.parent.assertEqual(result.logits.shape     ,				(self.batch_size, self.seq_length, self.num_labels)						)







     def 							lowercase__				(			self		: Optional[int]						):





        """simple docstring"""




        lowercase_      :Any         =			self.prepare_config_and_inputs()
        (
            (
            lowercase_
        )      ,							(
            lowercase_
        )      ,							(
            lowercase_
        )      ,							(
            lowercase_
        )      ,							(
            lowercase_
        )      ,							(
            lowercase_
        )      ,							
        )      :str         =			config_and_inputs
        lowercase_      :List[str]         =			{"input_ids": input_ids, "attention_mask": input_mask}
        return config, inputs_dict







@require_tf
class 				a_       (    _lowerCAmelCase     ,						_lowerCAmelCase     ,						unittest.TestCase							):
     __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 							lowercase__				(			self		: List[Any]						):





        """simple docstring"""




        lowercase_      :Optional[int]         =			TFEsmModelTester(self						)
        lowercase_      :Optional[Any]         =			ConfigTester(self     ,				config_class=lowercase     ,				hidden_size=37						)





     def 							lowercase__				(			self		: List[Any]						):





        """simple docstring"""




        self.config_tester.run_common_tests()





     def 							lowercase__				(			self		: List[Any]						):





        """simple docstring"""




        lowercase_      :List[Any]         =			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowercase						)





     def 							lowercase__				(			self		: int						):





        """simple docstring"""




        lowercase_      :Tuple         =			self.model_tester.prepare_config_and_inputs_for_decoder()
        self.model_tester.create_and_check_model_as_decoder(*lowercase						)





     def 							lowercase__				(			self		: Optional[int]						):





        """simple docstring"""




        lowercase_      :Optional[Any]         =			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_lm(*lowercase						)





     def 							lowercase__				(			self		: int						):





        """simple docstring"""




        lowercase_      :List[str]         =			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_token_classification(*lowercase						)





     @slow
     def 							lowercase__				(			self		: List[str]						):





        """simple docstring"""




        for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowercase_      :Tuple         =			TFEsmModel.from_pretrained(lowercase						)
           self.assertIsNotNone(lowercase						)





     @unittest.skip("Protein models do not support embedding resizing."						)
     def 							lowercase__				(			self		: Tuple						):





        """simple docstring"""




        pass





     @unittest.skip("Protein models do not support embedding resizing."						)
     def 							lowercase__				(			self		: Union[str, Any]						):





        """simple docstring"""




        pass







     def 							lowercase__				(			self		: str						):





        """simple docstring"""




        lowercase_      ,							lowercase_      :Union[str, Any]         =			self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
           lowercase_      :List[str]         =			model_class(lowercase						)
           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
              lowercase_      :str         =			model.get_bias()
              assert isinstance(lowercase     ,				lowercase						)
              for k, v in name.items():
                 assert isinstance(lowercase     ,				tf.Variable						)
           else:
              lowercase_      :str         =			model.get_output_embeddings()
              assert x is None
              lowercase_      :Union[str, Any]         =			model.get_bias()
              assert name is None







@require_tf
class 				a_       (    unittest.TestCase							):





     @slow
     def 							lowercase__				(			self		: List[str]						):





        """simple docstring"""




        lowercase_      :Any         =			TFEsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D"						)

        lowercase_      :Tuple         =			tf.constant([[0, 1, 2, 3, 4, 5]]						)
        lowercase_      :Tuple         =			model(lowercase						)[0]
        lowercase_      :Union[str, Any]         =			[1, 6, 33]
        self.assertEqual(list(output.numpy().shape						)     ,				lowercase						)
        # compare the actual values for a slice.
        lowercase_      :Dict         =			tf.constant(
            [
                [
                    [8.92_15_18, -10.58_98_14, -6.4_67_13_07],
                    [-6.3_96_71_56, -13.91_13_77, -1.1_21_19_15],
                    [-7.78_12_47, -13.95_15_57, -3.74_05_92],
                ]
            ]						)
        self.assertTrue(numpy.allclose(output[:, :3, :3].numpy()     ,				expected_slice.numpy()     ,				atol=1e-2						)						)







     @slow
     def 							lowercase__				(			self		: Union[str, Any]						):





        """simple docstring"""




        lowercase_      :int         =			TFEsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D"						)

        lowercase_      :Dict         =			tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]						)
        lowercase_      :List[str]         =			model(lowercase						)[0]
        # compare the actual values for a slice.
        lowercase_      :Optional[Any]         =			tf.constant(
            [
                [
                    [0.14_44_30_92, 0.54_12_53_27, 0.3_24_77_39],
                    [0.30_34_04_84, 0.00_52_66_76, 0.31_07_77_22],
                    [0.32_27_80_43, -0.24_98_70_96, 0.3_41_46_28],
                ]
            ]						)
        self.assertTrue(numpy.allclose(output[:, :3, :3].numpy()     ,				expected_slice.numpy()     ,				atol=1e-4						)						)









'''simple docstring'''


def 							UpperCAmelCase_  (						__lowerCamelCase : str     ,__lowerCamelCase : str			):
   lowercase_      :Optional[Any]         =			len(__lowerCamelCase			)
   lowercase_      :List[Any]         =			[]
   for i in range(len(__lowerCamelCase			) - pat_len + 1			):
      lowercase_      :Dict         =			True
      for j in range(__lowerCamelCase			):
         if s[i + j] != pattern[j]:
            lowercase_      :int         =			False
            break
      if match_found:
         position.append(__lowerCamelCase			)
   return position


if __name__ == "__main__":
 assert naive_pattern_search('''ABCDEFG''', '''DE''') == [3]
 print(naive_pattern_search('''ABAAABCDBBABCDDEBCABC''', '''ABC'''))


