'''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						:						Union[str, Any]    ,							a						:						Optional[int]    ,							):





         """simple docstring"""



         __lowerCamelCase            =    parent
         __lowerCamelCase            =    13
         __lowerCamelCase            =    7
         __lowerCamelCase            =    True
         __lowerCamelCase            =    True
         __lowerCamelCase            =    True
         __lowerCamelCase            =    99
         __lowerCamelCase            =    32
         __lowerCamelCase            =    2
         __lowerCamelCase            =    4
         __lowerCamelCase            =    37
         __lowerCamelCase            =    '''gelu'''
         __lowerCamelCase            =    0.1
         __lowerCamelCase            =    0.1
         __lowerCamelCase            =    5_12
         __lowerCamelCase            =    16
         __lowerCamelCase            =    2
         __lowerCamelCase            =    0.02
         __lowerCamelCase            =    3
         __lowerCamelCase            =    4
         __lowerCamelCase            =    None






     def   SCREAMING_SNAKE_CASE__  (					self						:						Any       ):





         """simple docstring"""



         __lowerCamelCase            =    ids_tensor([self.batch_size, self.seq_length]    ,							self.vocab_size       )

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

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

         __lowerCamelCase            =    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[int]       ):





         """simple docstring"""



         (
             (
             __lowerCamelCase
         )      ,    (
             __lowerCamelCase
         )      ,    (
             __lowerCamelCase
         )      ,    (
             __lowerCamelCase
         )      ,    (
             __lowerCamelCase
         )      ,    (
             __lowerCamelCase
         )      ,    
         )            =    self.prepare_config_and_inputs()

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





         """simple docstring"""



         __lowerCamelCase            =    TFEsmModel(config=a       )
         __lowerCamelCase            =    {'''input_ids''': input_ids, '''attention_mask''': input_mask}
         __lowerCamelCase            =    model(a       )

         __lowerCamelCase            =    [input_ids, input_mask]
         __lowerCamelCase            =    model(a       )

         __lowerCamelCase            =    model(a       )

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






     def   SCREAMING_SNAKE_CASE__  (					self						:						int    ,							a						:						Dict    ,							a						:						Tuple    ,							a						:						List[str]    ,							a						:						Dict    ,							a						:						int    ,							a						:						List[str]    ,							a						:						str    ,							a						:						int    ,							):





         """simple docstring"""



         __lowerCamelCase            =    True

         __lowerCamelCase            =    TFEsmModel(config=a       )
         __lowerCamelCase            =    {
             '''input_ids''': input_ids,
             '''attention_mask''': input_mask,
             '''encoder_hidden_states''': encoder_hidden_states,
             '''encoder_attention_mask''': encoder_attention_mask,
         }
         __lowerCamelCase            =    model(a       )

         __lowerCamelCase            =    [input_ids, input_mask]
         __lowerCamelCase            =    model(a    ,							encoder_hidden_states=a       )

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

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






     def   SCREAMING_SNAKE_CASE__  (					self						:						Tuple    ,							a						:						int    ,							a						:						Any    ,							a						:						Union[str, Any]    ,							a						:						Optional[Any]    ,							a						:						int    ,							a						:						int       ):





         """simple docstring"""



         __lowerCamelCase            =    TFEsmForMaskedLM(config=a       )
         __lowerCamelCase            =    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[int]    ,							a						:						List[Any]    ,							a						:						Tuple    ,							a						:						Optional[Any]    ,							a						:						Optional[int]    ,							a						:						Any    ,							a						:						Optional[int]       ):





         """simple docstring"""



         __lowerCamelCase            =    self.num_labels
         __lowerCamelCase            =    TFEsmForTokenClassification(config=a       )
         __lowerCamelCase            =    {'''input_ids''': input_ids, '''attention_mask''': input_mask}
         __lowerCamelCase            =    model(a       )
         self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, self.seq_length, self.num_labels)       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[Any]       ):





         """simple docstring"""



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




@require_tf
class        a__ (  UpperCAmelCase__				,  UpperCAmelCase__				,  unittest.TestCase					):
     lowerCamelCase    :	Tuple				=(
         (
             TFEsmModel,
             TFEsmForMaskedLM,
             TFEsmForSequenceClassification,
             TFEsmForTokenClassification,
         )
         if is_tf_available()
         else ()
     )
     lowerCamelCase    :	List[str]				=(
         {
             "feature-extraction": TFEsmModel,
             "fill-mask": TFEsmForMaskedLM,
             "text-classification": TFEsmForSequenceClassification,
             "token-classification": TFEsmForTokenClassification,
             "zero-shot": TFEsmForSequenceClassification,
         }
         if is_tf_available()
         else {}
     )
     lowerCamelCase    :	List[str]				=False
     lowerCamelCase    :	Union[str, Any]				=False






     def   SCREAMING_SNAKE_CASE__  (					self						:						Union[str, Any]       ):





         """simple docstring"""



         __lowerCamelCase            =    TFEsmModelTester(self       )
         __lowerCamelCase            =    ConfigTester(self    ,							config_class=a    ,							hidden_size=37       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						str       ):





         """simple docstring"""



         self.config_tester.run_common_tests()






     def   SCREAMING_SNAKE_CASE__  (					self						:						str       ):





         """simple docstring"""



         __lowerCamelCase            =    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*a       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						Any       ):





         """simple docstring"""



         __lowerCamelCase            =    self.model_tester.prepare_config_and_inputs_for_decoder()
         self.model_tester.create_and_check_model_as_decoder(*a       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						Dict       ):





         """simple docstring"""



         __lowerCamelCase            =    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_masked_lm(*a       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						int       ):





         """simple docstring"""



         __lowerCamelCase            =    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_token_classification(*a       )






     @slow
     def   SCREAMING_SNAKE_CASE__  (					self						:						Tuple       ):





         """simple docstring"""



         for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             __lowerCamelCase            =    TFEsmModel.from_pretrained(a       )
             self.assertIsNotNone(a       )






     @unittest.skip('''Protein models do not support embedding resizing.'''       )
     def   SCREAMING_SNAKE_CASE__  (					self						:						str       ):





         """simple docstring"""



         pass






     @unittest.skip('''Protein models do not support embedding resizing.'''       )
     def   SCREAMING_SNAKE_CASE__  (					self						:						List[str]       ):





         """simple docstring"""



         pass






     def   SCREAMING_SNAKE_CASE__  (					self						:						List[str]       ):





         """simple docstring"""



         __lowerCamelCase      ,    __lowerCamelCase            =    self.model_tester.prepare_config_and_inputs_for_common()

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




@require_tf
class        a__ (  unittest.TestCase					):






     @slow
     def   SCREAMING_SNAKE_CASE__  (					self						:						str       ):





         """simple docstring"""



         __lowerCamelCase            =    TFEsmForMaskedLM.from_pretrained('''facebook/esm2_t6_8M_UR50D'''       )

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





         """simple docstring"""



         __lowerCamelCase            =    TFEsmModel.from_pretrained('''facebook/esm2_t6_8M_UR50D'''       )

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




import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
__UpperCAmelCase					=pytest.mark.integration


__UpperCAmelCase					={"comet"}
__UpperCAmelCase					=importlib.util.find_spec("fairseq") is not None

__UpperCAmelCase					={"code_eval"}
__UpperCAmelCase					=os.name == "nt"

__UpperCAmelCase					={"bertscore", "frugalscore", "perplexity"}
__UpperCAmelCase					=importlib.util.find_spec("transformers") is not None






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       Any:
    @wraps(UpperCamelCase__							)
    def wrapper(self							,    UpperCamelCase__							):
        if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
            self.skipTest('''"test requires Fairseq"'''							)
        else:
            test_case(self							,    UpperCamelCase__							)

    return wrapper






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       Any:
    @wraps(UpperCamelCase__							)
    def wrapper(self							,    UpperCamelCase__							):
        if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
            self.skipTest('''"test requires transformers"'''							)
        else:
            test_case(self							,    UpperCamelCase__							)

    return wrapper






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       List[Any]:
    @wraps(UpperCamelCase__							)
    def wrapper(self							,    UpperCamelCase__							):
        if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
            self.skipTest('''"test not supported on Windows"'''							)
        else:
            test_case(self							,    UpperCamelCase__							)

    return wrapper






def __lowerCAmelCase					(				)      ->       Any:
    __lowerCamelCase            =    [metric_dir.split(os.sep							)[-2] for metric_dir in glob.glob('''./metrics/*/'''							)]
    return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished




@parameterized.named_parameters(get_local_metric_names()					)
@for_all_test_methods(
    UpperCAmelCase__				,  UpperCAmelCase__				,  UpperCAmelCase__					)
@local
class        a__ (  parameterized.TestCase					):
     lowerCamelCase    :	str				={}
     lowerCamelCase    :	Union[str, Any]				=None






     @pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning'''       )
     @pytest.mark.filterwarnings('''ignore:load_metric is deprecated:FutureWarning'''       )
     def   SCREAMING_SNAKE_CASE__  (					self						:						Tuple    ,							a						:						List[Any]       ):





         """simple docstring"""



         __lowerCamelCase            =    '''[...]'''
         __lowerCamelCase            =    importlib.import_module(
             datasets.load.metric_module_factory(os.path.join('''metrics'''    ,							a       )       ).module_path       )
         __lowerCamelCase            =    datasets.load.import_main_class(metric_module.__name__    ,							dataset=a       )
         # check parameters
         __lowerCamelCase            =    inspect.signature(metric._compute       ).parameters
         self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()       )       )  # no **kwargs
         # run doctest
         with self.patch_intensive_calls(a    ,							metric_module.__name__       ):
             with self.use_local_metrics():
                 try:
                     __lowerCamelCase            =    doctest.testmod(a    ,							verbose=a    ,							raise_on_error=a       )
                 except doctest.UnexpectedException as e:
                     raise e.exc_info[1]  # raise the exception that doctest caught
         self.assertEqual(results.failed    ,							0       )
         self.assertGreater(results.attempted    ,							1       )






     @slow
     def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[Any]    ,							a						:						Optional[int]       ):





         """simple docstring"""



         __lowerCamelCase            =    '''[...]'''
         __lowerCamelCase            =    importlib.import_module(
             datasets.load.metric_module_factory(os.path.join('''metrics'''    ,							a       )       ).module_path       )
         # run doctest
         with self.use_local_metrics():
             __lowerCamelCase            =    doctest.testmod(a    ,							verbose=a    ,							raise_on_error=a       )
         self.assertEqual(results.failed    ,							0       )
         self.assertGreater(results.attempted    ,							1       )






     @contextmanager
     def   SCREAMING_SNAKE_CASE__  (					self						:						Any    ,							a						:						Optional[Any]    ,							a						:						Any       ):





         """simple docstring"""



         if metric_name in self.INTENSIVE_CALLS_PATCHER:
             with self.INTENSIVE_CALLS_PATCHER[metric_name](a       ):
                 yield
         else:
             yield






     @contextmanager
     def   SCREAMING_SNAKE_CASE__  (					self						:						Dict       ):





         """simple docstring"""



         def load_local_metric(a						:						List[str]    ,							*a						:						Optional[int]    ,							**a						:						Tuple       ):
             return load_metric(os.path.join('''metrics'''    ,							a       )    ,							*a    ,							**a       )

         with patch('''datasets.load_metric'''       ) as mock_load_metric:
             __lowerCamelCase            =    load_local_metric
             yield






     @classmethod
     def   SCREAMING_SNAKE_CASE__  (					cls						:						List[str]    ,							a						:						Tuple       ):





         """simple docstring"""



         def wrapper(a						:						List[Any]       ):
             __lowerCamelCase            =    contextmanager(a       )
             __lowerCamelCase            =    patcher
             return patcher

         return wrapper






@LocalMetricTest.register_intensive_calls_patcher('''bleurt'''							)
def __lowerCAmelCase					(				UpperCamelCase__							)      ->       Union[str, Any]:
    import tensorflow.compat.va as tf
    from bleurt.score import Predictor

    tf.flags.DEFINE_string('''sv'''							,    ''''''							,    ''''''							)  # handle pytest cli flags




    class        a__ (  UpperCAmelCase__					):






         def   SCREAMING_SNAKE_CASE__  (					self						:						Tuple    ,							a						:						Dict       ):





             """simple docstring"""



             assert len(input_dict['''input_ids''']       ) == 2
             return np.array([1.03, 1.04]       )

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
    with patch('''bleurt.score._create_predictor'''							) as mock_create_predictor:
        __lowerCamelCase            =    MockedPredictor()
        yield






@LocalMetricTest.register_intensive_calls_patcher('''bertscore'''							)
def __lowerCAmelCase					(				UpperCamelCase__							)      ->       Tuple:
    import torch

    def bert_cos_score_idf(UpperCamelCase__							,    UpperCamelCase__							,    *UpperCamelCase__							,    **UpperCamelCase__							):
        return torch.tensor([[1.0, 1.0, 1.0]] * len(UpperCamelCase__							)							)

    # mock get_model which is supposed to do download a bert model
    # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
    with patch('''bert_score.scorer.get_model'''							), patch(
        '''bert_score.scorer.bert_cos_score_idf'''							) as mock_bert_cos_score_idf:
        __lowerCamelCase            =    bert_cos_score_idf
        yield






@LocalMetricTest.register_intensive_calls_patcher('''comet'''							)
def __lowerCAmelCase					(				UpperCamelCase__							)      ->       List[str]:
    def load_from_checkpoint(UpperCamelCase__							):




        class        a__ :






             def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[int]    ,							a						:						str    ,							*a						:						int    ,							**a						:						Tuple       ):





                 """simple docstring"""



                 assert len(a       ) == 2
                 __lowerCamelCase            =    [0.19, 0.92]
                 return scores, sum(a       ) / len(a       )
        return Model()

    # mock load_from_checkpoint which is supposed to do download a bert model
    # mock load_from_checkpoint which is supposed to do download a bert model
    with patch('''comet.download_model'''							) as mock_download_model:
        __lowerCamelCase            =    None
        with patch('''comet.load_from_checkpoint'''							) as mock_load_from_checkpoint:
            __lowerCamelCase            =    load_from_checkpoint
            yield






def __lowerCAmelCase					(				)      ->       List[Any]:
    __lowerCamelCase            =    load_metric(os.path.join('''metrics'''							,    '''seqeval'''							)							)
    __lowerCamelCase            =    '''ERROR'''
    __lowerCamelCase            =    f"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}"""
    with pytest.raises(UpperCamelCase__							,    match=re.escape(UpperCamelCase__							)							):
        metric.compute(predictions=[]							,    references=[]							,    scheme=UpperCamelCase__							)
