

"""simple docstring"""





from collections import OrderedDict
from typing import Any, Mapping, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...feature_extraction_utils import FeatureExtractionMixin
from ...onnx import OnnxConfig
from ...onnx.utils import compute_effective_axis_dimension
from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import TensorType, logging


_a							=							logging.get_logger(__name__)

_a							=							{
    'deepmind/language-perceiver': 'https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json',
    # See all Perceiver models at https://huggingface.co/models?filter=perceiver
}




class  _lowerCAmelCase  (     lowercase       ):







 """simple docstring"""







 __UpperCAmelCase     : List[str]       		=     "perceiver"


 def __init__(      self							:      List[str], UpperCAmelCase__							:      Tuple=2_5_6, UpperCAmelCase__							:      List[str]=1_2_8_0, UpperCAmelCase__							:      Optional[int]=7_6_8, UpperCAmelCase__							:      Tuple=1, UpperCAmelCase__							:      int=2_6, UpperCAmelCase__							:      Optional[Any]=8, UpperCAmelCase__							:      Tuple=8, UpperCAmelCase__							:      int=None, UpperCAmelCase__							:      List[str]=None, UpperCAmelCase__							:      Optional[Any]="kv", UpperCAmelCase__							:      int=1, UpperCAmelCase__							:      int=1, UpperCAmelCase__							:      Union[str, Any]="gelu", UpperCAmelCase__							:      int=0.1, UpperCAmelCase__							:      Union[str, Any]=0.02, UpperCAmelCase__							:      str=1E-12, UpperCAmelCase__							:      Tuple=True, UpperCAmelCase__							:      List[str]=2_6_2, UpperCAmelCase__							:      Tuple=2_0_4_8, UpperCAmelCase__							:      str=5_6, UpperCAmelCase__							:      Optional[Any]=[3_6_8, 4_9_6], UpperCAmelCase__							:      List[str]=1_6, UpperCAmelCase__							:      str=1_9_2_0, UpperCAmelCase__							:      Tuple=1_6, UpperCAmelCase__							:      Dict=[1, 1_6, 2_2_4, 2_2_4], **UpperCAmelCase__							:      Any, ):
    super().__init__(**UpperCAmelCase__     )

    __lowercase								=						num_latents
    __lowercase								=						d_latents
    __lowercase								=						d_model
    __lowercase								=						num_blocks
    __lowercase								=						num_self_attends_per_block
    __lowercase								=						num_self_attention_heads
    __lowercase								=						num_cross_attention_heads
    __lowercase								=						qk_channels
    __lowercase								=						v_channels
    __lowercase								=						cross_attention_shape_for_attention
    __lowercase								=						self_attention_widening_factor
    __lowercase								=						cross_attention_widening_factor
    __lowercase								=						hidden_act
    __lowercase								=						attention_probs_dropout_prob
    __lowercase								=						initializer_range
    __lowercase								=						layer_norm_eps
    __lowercase								=						use_query_residual
    # masked language modeling attributes
    __lowercase								=						vocab_size
    __lowercase								=						max_position_embeddings
    # image classification attributes
    __lowercase								=						image_size
    # flow attributes
    __lowercase								=						train_size
    # multimodal autoencoding attributes
    __lowercase								=						num_frames
    __lowercase								=						audio_samples_per_frame
    __lowercase								=						samples_per_patch
    __lowercase								=						output_shape







class  _lowerCAmelCase  (     lowercase       ):







 """simple docstring"""







 @property
 def  _lowercase			(      self							:      Union[str, Any]     ):
    if self.task == "multiple-choice":
       __lowercase								=						{0: "batch", 1: "choice", 2: "sequence"}
    else:
       __lowercase								=						{0: "batch", 1: "sequence"}
    return OrderedDict(
        [
            ("inputs", dynamic_axis),
            ("attention_mask", dynamic_axis),
        ]     )


 @property
 def  _lowercase			(      self							:      Any     ):
    return 1E-4



 def  _lowercase			(      self							:      Dict, UpperCAmelCase__							:      Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"], UpperCAmelCase__							:      int = -1, UpperCAmelCase__							:      int = -1, UpperCAmelCase__							:      int = -1, UpperCAmelCase__							:      bool = False, UpperCAmelCase__							:      Optional[TensorType] = None, UpperCAmelCase__							:      int = 3, UpperCAmelCase__							:      int = 4_0, UpperCAmelCase__							:      int = 4_0, ):
    # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified

    if isinstance(UpperCAmelCase__, UpperCAmelCase__     ):
       # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
       __lowercase								=						compute_effective_axis_dimension(
           UpperCAmelCase__, fixed_dimension=OnnxConfig.default_fixed_batch, num_token_to_add=0     )
       # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
       __lowercase								=						preprocessor.num_special_tokens_to_add(UpperCAmelCase__     )
       __lowercase								=						compute_effective_axis_dimension(
           UpperCAmelCase__, fixed_dimension=OnnxConfig.default_fixed_sequence, num_token_to_add=UpperCAmelCase__     )
       # Generate dummy inputs according to compute batch and sequence
       __lowercase								=						[" ".join(["a"]     ) * seq_length] * batch_size
       __lowercase								=						dict(preprocessor(UpperCAmelCase__, return_tensors=UpperCAmelCase__     )     )
       __lowercase								=						inputs.pop("input_ids"     )
       return inputs
    elif isinstance(UpperCAmelCase__, UpperCAmelCase__     ) and preprocessor.model_input_names[0] == "pixel_values":
       # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
       __lowercase								=						compute_effective_axis_dimension(UpperCAmelCase__, fixed_dimension=OnnxConfig.default_fixed_batch     )
       __lowercase								=						self._generate_dummy_images(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__     )
       __lowercase								=						dict(preprocessor(images=UpperCAmelCase__, return_tensors=UpperCAmelCase__     )     )
       __lowercase								=						inputs.pop("pixel_values"     )
       return inputs
    else:
       raise ValueError(
           "Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor."     )







"""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
_a							=							pytest.mark.integration


_a							=							{'comet'}
_a							=							importlib.util.find_spec('fairseq') is not None

_a							=							{'code_eval'}
_a							=							os.name == 'nt'

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




def   _A  (  UpperCamelCase_					:	Dict)     ->						Any:
   '''simple docstring'''


   @wraps(UpperCamelCase_)
   def wrapper(self					:	Dict,      UpperCamelCase_					:	Dict):
      if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
         self.skipTest("\"test requires Fairseq\"")
      else:
         test_case(self,      UpperCamelCase_)

   return wrapper




def   _A  (  UpperCamelCase_					:	Dict)     ->						int:
   '''simple docstring'''


   @wraps(UpperCamelCase_)
   def wrapper(self					:	int,      UpperCamelCase_					:	str):
      if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
         self.skipTest("\"test requires transformers\"")
      else:
         test_case(self,      UpperCamelCase_)

   return wrapper




def   _A  (  UpperCamelCase_					:	Tuple)     ->						str:
   '''simple docstring'''


   @wraps(UpperCamelCase_)
   def wrapper(self					:	Optional[int],      UpperCamelCase_					:	Optional[Any]):
      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   _A  (  )     ->						str:
   '''simple docstring'''


   __lowercase								=						[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(
    lowercase					,lowercase					,lowercase       )
@local
class  _lowerCAmelCase  (     parameterized.TestCase       ):







 """simple docstring"""







 __UpperCAmelCase     : Optional[int]       		=     {}
 __UpperCAmelCase     : Tuple       		=     None


 @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning"     )
 @pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning"     )
 def  _lowercase			(      self							:      Dict, UpperCAmelCase__							:      int     ):
    __lowercase								=						"[...]"
    __lowercase								=						importlib.import_module(
        datasets.load.metric_module_factory(os.path.join("metrics", UpperCAmelCase__     )     ).module_path     )
    __lowercase								=						datasets.load.import_main_class(metric_module.__name__, dataset=UpperCAmelCase__     )
    # check parameters
    __lowercase								=						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(UpperCAmelCase__, metric_module.__name__     ):
       with self.use_local_metrics():
          try:
             __lowercase								=						doctest.testmod(UpperCAmelCase__, verbose=UpperCAmelCase__, raise_on_error=UpperCAmelCase__     )
          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  _lowercase			(      self							:      List[Any], UpperCAmelCase__							:      Optional[Any]     ):
    __lowercase								=						"[...]"
    __lowercase								=						importlib.import_module(
        datasets.load.metric_module_factory(os.path.join("metrics", UpperCAmelCase__     )     ).module_path     )
    # run doctest
    with self.use_local_metrics():
       __lowercase								=						doctest.testmod(UpperCAmelCase__, verbose=UpperCAmelCase__, raise_on_error=UpperCAmelCase__     )
    self.assertEqual(results.failed, 0     )
    self.assertGreater(results.attempted, 1     )


 @contextmanager
 def  _lowercase			(      self							:      List[Any], UpperCAmelCase__							:      Any, UpperCAmelCase__							:      Tuple     ):
    if metric_name in self.INTENSIVE_CALLS_PATCHER:
       with self.INTENSIVE_CALLS_PATCHER[metric_name](UpperCAmelCase__     ):
          yield
    else:
       yield


 @contextmanager
 def  _lowercase			(      self							:      List[Any]     ):
    def load_local_metric(UpperCAmelCase__							:      Any, *UpperCAmelCase__							:      List[Any], **UpperCAmelCase__							:      Any     ):
       return load_metric(os.path.join("metrics", UpperCAmelCase__     ), *UpperCAmelCase__, **UpperCAmelCase__     )

    with patch("datasets.load_metric"     ) as mock_load_metric:
       __lowercase								=						load_local_metric
       yield



 @classmethod
 def  _lowercase			(      cls							:      Optional[Any], UpperCAmelCase__							:      List[Any]     ):
    def wrapper(UpperCAmelCase__							:      Tuple     ):
       __lowercase								=						contextmanager(UpperCAmelCase__     )
       __lowercase								=						patcher
       return patcher

    return wrapper







@LocalMetricTest.register_intensive_calls_patcher("bleurt")
def   _A  (  UpperCamelCase_					:	Any)     ->						Optional[Any]:
   '''simple docstring'''


   import tensorflow.compat.va as tf
   from bleurt.score import Predictor

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




   class  _lowerCAmelCase  (     lowercase       ):







    """simple docstring"""







    def  _lowercase			(      self							:      Tuple, UpperCAmelCase__							:      Tuple     ):
       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:
      __lowercase								=						MockedPredictor()
      yield




@LocalMetricTest.register_intensive_calls_patcher("bertscore")
def   _A  (  UpperCamelCase_					:	Tuple)     ->						int:
   '''simple docstring'''


   import torch

   def bert_cos_score_idf(UpperCamelCase_					:	Tuple,      UpperCamelCase_					:	str,      *UpperCamelCase_					:	Optional[Any],      **UpperCamelCase_					:	Dict):
      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:
      __lowercase								=						bert_cos_score_idf
      yield




@LocalMetricTest.register_intensive_calls_patcher("comet")
def   _A  (  UpperCamelCase_					:	Tuple)     ->						List[Any]:
   '''simple docstring'''


   def load_from_checkpoint(UpperCamelCase_					:	Tuple):




      class  _lowerCAmelCase  :







       """simple docstring"""







       def  _lowercase			(      self							:      str, UpperCAmelCase__							:      int, *UpperCAmelCase__							:      Dict, **UpperCAmelCase__							:      Dict     ):
          assert len(UpperCAmelCase__     ) == 2
          __lowercase								=						[0.19, 0.92]
          return scores, sum(UpperCAmelCase__     ) / len(UpperCAmelCase__     )







      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:
      __lowercase								=						None
      with patch("comet.load_from_checkpoint") as mock_load_from_checkpoint:
         __lowercase								=						load_from_checkpoint
         yield




def   _A  (  )     ->						Tuple:
   '''simple docstring'''


   __lowercase								=						load_metric(os.path.join("metrics",      "seqeval"))
   __lowercase								=						"ERROR"
   __lowercase								=						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_)




