
"""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]       ,      UpperCAmelCase_ :							Optional[int]       ,      )->  Tuple:







              """simple docstring"""
              UpperCamelCase					 =		parent
              UpperCamelCase					 =		13
              UpperCamelCase					 =		7
              UpperCamelCase					 =		True
              UpperCamelCase					 =		True
              UpperCamelCase					 =		True
              UpperCamelCase					 =		99
              UpperCamelCase					 =		32
              UpperCamelCase					 =		2
              UpperCamelCase					 =		4
              UpperCamelCase					 =		37
              UpperCamelCase					 =		"gelu"
              UpperCamelCase					 =		0.1
              UpperCamelCase					 =		0.1
              UpperCamelCase					 =		512
              UpperCamelCase					 =		16
              UpperCamelCase					 =		2
              UpperCamelCase					 =		0.02
              UpperCamelCase					 =		3
              UpperCamelCase					 =		4
              UpperCamelCase					 =		None






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







              """simple docstring"""
              UpperCamelCase					 =		ids_tensor([self.batch_size, self.seq_length]       ,      self.vocab_size			)

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

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

              UpperCamelCase					 =		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 :							Optional[Any]			)->  Dict:







              """simple docstring"""
              (
                  (
                  UpperCamelCase
              ) ,       (
                  UpperCamelCase
              ) ,       (
                  UpperCamelCase
              ) ,       (
                  UpperCamelCase
              ) ,       (
                  UpperCamelCase
              ) ,       (
                  UpperCamelCase
              ) ,       
              )					 =		self.prepare_config_and_inputs()

              UpperCamelCase					 =		True
              UpperCamelCase					 =		floats_tensor([self.batch_size, self.seq_length, self.hidden_size]			)
              UpperCamelCase					 =		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 :							Tuple       ,      UpperCAmelCase_ :							str       ,      UpperCAmelCase_ :							int       ,      UpperCAmelCase_ :							Union[str, Any]       ,      UpperCAmelCase_ :							Any       ,      UpperCAmelCase_ :							Optional[int]       ,      UpperCAmelCase_ :							int			)->  Union[str, Any]:







              """simple docstring"""
              UpperCamelCase					 =		TFEsmModel(config=UpperCAmelCase_			)
              UpperCamelCase					 =		{"input_ids": input_ids, "attention_mask": input_mask}
              UpperCamelCase					 =		model(UpperCAmelCase_			)

              UpperCamelCase					 =		[input_ids, input_mask]
              UpperCamelCase					 =		model(UpperCAmelCase_			)

              UpperCamelCase					 =		model(UpperCAmelCase_			)

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






       def 	_SCREAMING_SNAKE_CASE       (  self :							List[Any]       ,      UpperCAmelCase_ :							Union[str, Any]       ,      UpperCAmelCase_ :							Optional[int]       ,      UpperCAmelCase_ :							Dict       ,      UpperCAmelCase_ :							Any       ,      UpperCAmelCase_ :							Tuple       ,      UpperCAmelCase_ :							Union[str, Any]       ,      UpperCAmelCase_ :							Any       ,      UpperCAmelCase_ :							List[str]       ,      )->  Any:







              """simple docstring"""
              UpperCamelCase					 =		True

              UpperCamelCase					 =		TFEsmModel(config=UpperCAmelCase_			)
              UpperCamelCase					 =		{
                  "input_ids": input_ids,
                  "attention_mask": input_mask,
                  "encoder_hidden_states": encoder_hidden_states,
                  "encoder_attention_mask": encoder_attention_mask,
              }
              UpperCamelCase					 =		model(UpperCAmelCase_			)

              UpperCamelCase					 =		[input_ids, input_mask]
              UpperCamelCase					 =		model(UpperCAmelCase_       ,      encoder_hidden_states=UpperCAmelCase_			)

              # Also check the case where encoder outputs are not passed
              UpperCamelCase					 =		model(UpperCAmelCase_       ,      attention_mask=UpperCAmelCase_			)

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






       def 	_SCREAMING_SNAKE_CASE       (  self :							Dict       ,      UpperCAmelCase_ :							List[str]       ,      UpperCAmelCase_ :							Tuple       ,      UpperCAmelCase_ :							Optional[int]       ,      UpperCAmelCase_ :							Optional[int]       ,      UpperCAmelCase_ :							Union[str, Any]       ,      UpperCAmelCase_ :							int			)->  List[Any]:







              """simple docstring"""
              UpperCamelCase					 =		TFEsmForMaskedLM(config=UpperCAmelCase_			)
              UpperCamelCase					 =		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 :							Optional[Any]       ,      UpperCAmelCase_ :							Tuple       ,      UpperCAmelCase_ :							str       ,      UpperCAmelCase_ :							Dict       ,      UpperCAmelCase_ :							int       ,      UpperCAmelCase_ :							Tuple       ,      UpperCAmelCase_ :							Any			)->  str:







              """simple docstring"""
              UpperCamelCase					 =		self.num_labels
              UpperCamelCase					 =		TFEsmForTokenClassification(config=UpperCAmelCase_			)
              UpperCamelCase					 =		{"input_ids": input_ids, "attention_mask": input_mask}
              UpperCamelCase					 =		model(UpperCAmelCase_			)
              self.parent.assertEqual(result.logits.shape       ,      (self.batch_size, self.seq_length, self.num_labels)			)






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







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





@require_tf
class   __a  (      _lowerCAmelCase    ,     _lowerCAmelCase    ,     unittest.TestCase	):
       UpperCamelCase_		:					Union[str, Any]   =			(
           (
               TFEsmModel,
               TFEsmForMaskedLM,
               TFEsmForSequenceClassification,
               TFEsmForTokenClassification,
           )
           if is_tf_available()
           else ()
       )
       UpperCamelCase_		:					Union[str, Any]   =			(
           {
               '''feature-extraction''': TFEsmModel,
               '''fill-mask''': TFEsmForMaskedLM,
               '''text-classification''': TFEsmForSequenceClassification,
               '''token-classification''': TFEsmForTokenClassification,
               '''zero-shot''': TFEsmForSequenceClassification,
           }
           if is_tf_available()
           else {}
       )
       UpperCamelCase_		:					Any   =			False
       UpperCamelCase_		:					str   =			False






       def 	_SCREAMING_SNAKE_CASE       (  self :							Optional[int]			)->  Optional[int]:







              """simple docstring"""
              UpperCamelCase					 =		TFEsmModelTester(self			)
              UpperCamelCase					 =		ConfigTester(self       ,      config_class=UpperCAmelCase_       ,      hidden_size=37			)






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







              """simple docstring"""
              self.config_tester.run_common_tests()






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







              """simple docstring"""
              UpperCamelCase					 =		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_model(*UpperCAmelCase_			)






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







              """simple docstring"""
              UpperCamelCase					 =		self.model_tester.prepare_config_and_inputs_for_decoder()
              self.model_tester.create_and_check_model_as_decoder(*UpperCAmelCase_			)






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







              """simple docstring"""
              UpperCamelCase					 =		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase_			)






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







              """simple docstring"""
              UpperCamelCase					 =		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase_			)






       @slow
       def 	_SCREAMING_SNAKE_CASE       (  self :							Any			)->  Tuple:







              """simple docstring"""
              for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                     UpperCamelCase					 =		TFEsmModel.from_pretrained(UpperCAmelCase_			)
                     self.assertIsNotNone(UpperCAmelCase_			)






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







              """simple docstring"""
              pass






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







              """simple docstring"""
              pass






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







              """simple docstring"""
              UpperCamelCase ,       UpperCamelCase					 =		self.model_tester.prepare_config_and_inputs_for_common()

              for model_class in self.all_model_classes:
                     UpperCamelCase					 =		model_class(UpperCAmelCase_			)
                     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
                            UpperCamelCase					 =		model.get_bias()
                            assert isinstance(UpperCAmelCase_       ,      UpperCAmelCase_			)
                            for k, v in name.items():
                                   assert isinstance(UpperCAmelCase_       ,      tf.Variable			)
                     else:
                            UpperCamelCase					 =		model.get_output_embeddings()
                            assert x is None
                            UpperCamelCase					 =		model.get_bias()
                            assert name is None





@require_tf
class   __a  (      unittest.TestCase	):






       @slow
       def 	_SCREAMING_SNAKE_CASE       (  self :							List[str]			)->  Optional[Any]:







              """simple docstring"""
              UpperCamelCase					 =		TFEsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D"			)

              UpperCamelCase					 =		tf.constant([[0, 1, 2, 3, 4, 5]]			)
              UpperCamelCase					 =		model(UpperCAmelCase_			)[0]
              UpperCamelCase					 =		[1, 6, 33]
              self.assertEqual(list(output.numpy().shape			)       ,      UpperCAmelCase_			)
              # compare the actual values for a slice.
              UpperCamelCase					 =		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 :							List[Any]			)->  List[Any]:







              """simple docstring"""
              UpperCamelCase					 =		TFEsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D"			)

              UpperCamelCase					 =		tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]			)
              UpperCamelCase					 =		model(UpperCAmelCase_			)[0]
              # compare the actual values for a slice.
              UpperCamelCase					 =		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			)			)







"""simple docstring"""


def 	lowerCamelCase__			(							UpperCAmelCase_		,      UpperCAmelCase_ = False				)->							bool:







       """simple docstring"""
       if n == 2:
              return True
       if not n % 2 or n < 2:
              return False
       if n > 5 and n % 10 not in (1, 3, 7, 9):  # can quickly check last digit
              return False
       if n > 3_31_70_44_06_46_79_88_73_85_96_19_81 and not allow_probable:
              raise ValueError(
                  "Warning: upper bound of deterministic test is exceeded. "
                  "Pass allow_probable=True to allow probabilistic test. "
                  "A return value of True indicates a probable prime."				)
       # array bounds provided by analysis
       UpperCamelCase					 =		[
           20_47,
           1_37_36_53,
           25_32_60_01,
           32_15_03_17_51,
           2_15_23_02_89_87_47,
           3_47_47_49_66_03_83,
           3_41_55_00_71_72_83_21,
           1,
           3_82_51_23_05_65_46_41_30_51,
           1,
           1,
           31_86_65_85_78_34_03_11_51_16_74_61,
           3_31_70_44_06_46_79_88_73_85_96_19_81,
       ]

       UpperCamelCase					 =		[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
       for idx, _p in enumerate(UpperCAmelCase_		,      1				):
              if n < _p:
                     # then we have our last prime to check
                     UpperCamelCase					 =		primes[:idx]
                     break
       UpperCamelCase ,       UpperCamelCase					 =		n - 1, 0
       # break up n -1 into a power of 2 (s) and
       # remaining odd component
       # essentially, solve for d * 2 ** s == n - 1
       while d % 2 == 0:
              d //= 2
              s += 1
       for prime in plist:
              UpperCamelCase					 =		False
              for r in range(UpperCAmelCase_				):
                     UpperCamelCase					 =		pow(UpperCAmelCase_		,      d * 2**r		,      UpperCAmelCase_				)
                     # see article for analysis explanation for m
                     if (r == 0 and m == 1) or ((m + 1) % n == 0):
                            UpperCamelCase					 =		True
                            # this loop will not determine compositeness
                            break
              if pr:
                     continue
              # if pr is False, then the above loop never evaluated to true,
              # and the n MUST be composite
              return False
       return True



def 	lowerCamelCase__			(							)->							None:







       """simple docstring"""
       assert not miller_rabin(5_61				)
       assert miller_rabin(5_63				)
       # 2047

       assert not miller_rabin(83_82_01				)
       assert miller_rabin(83_82_07				)
       # 1_373_653

       assert not miller_rabin(17_31_60_01				)
       assert miller_rabin(17_31_60_17				)
       # 25_326_001

       assert not miller_rabin(30_78_38_66_41				)
       assert miller_rabin(30_78_38_66_53				)
       # 3_215_031_751

       assert not miller_rabin(1_71_30_45_57_48_01				)
       assert miller_rabin(1_71_30_45_57_48_19				)
       # 2_152_302_898_747

       assert not miller_rabin(2_77_97_99_72_83_07				)
       assert miller_rabin(2_77_97_99_72_83_27				)
       # 3_474_749_660_383

       assert not miller_rabin(1_13_85_00_23_90_94_41				)
       assert miller_rabin(1_13_85_00_23_90_95_27				)
       # 341_550_071_728_321

       assert not miller_rabin(1_27_50_41_01_88_48_80_43_51				)
       assert miller_rabin(1_27_50_41_01_88_48_80_43_91				)
       # 3_825_123_056_546_413_051

       assert not miller_rabin(7_96_66_46_44_58_50_77_87_79_18_67				)
       assert miller_rabin(7_96_66_46_44_58_50_77_87_79_19_51				)
       # 318_665_857_834_031_151_167_461

       assert not miller_rabin(55_28_40_67_74_46_64_78_97_66_03_33				)
       assert miller_rabin(55_28_40_67_74_46_64_78_97_66_03_59				)
       # 3_317_044_064_679_887_385_961_981
       # upper limit for probabilistic test


if __name__ == "__main__":
      test_miller_rabin()





