
import unittest

from transformers import LiltConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import (
          LiltForQuestionAnswering,
          LiltForSequenceClassification,
          LiltForTokenClassification,
          LiltModel,
      )
      from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST





class 							A__		:
      def __init__(      self    ,  __magic_name__    ,  __magic_name__=1_3    ,  __magic_name__=7    ,  __magic_name__=True    ,  __magic_name__=True    ,  __magic_name__=True    ,  __magic_name__=True    ,  __magic_name__=9_9    ,  __magic_name__=2_4    ,  __magic_name__=2    ,  __magic_name__=6    ,  __magic_name__=3_7    ,  __magic_name__="gelu"    ,  __magic_name__=0.1    ,  __magic_name__=0.1    ,  __magic_name__=5_1_2    ,  __magic_name__=1_6    ,  __magic_name__=2    ,  __magic_name__=0.02    ,  __magic_name__=3    ,  __magic_name__=None    ,  __magic_name__=1_0_0_0    ,  ):
       lowerCamelCase		:	Union[str, Any]							=      parent
       lowerCamelCase		:	Union[str, Any]							=      batch_size
       lowerCamelCase		:	Tuple							=      seq_length
       lowerCamelCase		:	int							=      is_training
       lowerCamelCase		:	str							=      use_input_mask
       lowerCamelCase		:	List[Any]							=      use_token_type_ids
       lowerCamelCase		:	List[str]							=      use_labels
       lowerCamelCase		:	Optional[Any]							=      vocab_size
       lowerCamelCase		:	Tuple							=      hidden_size
       lowerCamelCase		:	Optional[Any]							=      num_hidden_layers
       lowerCamelCase		:	Dict							=      num_attention_heads
       lowerCamelCase		:	Any							=      intermediate_size
       lowerCamelCase		:	Optional[Any]							=      hidden_act
       lowerCamelCase		:	Optional[Any]							=      hidden_dropout_prob
       lowerCamelCase		:	int							=      attention_probs_dropout_prob
       lowerCamelCase		:	Union[str, Any]							=      max_position_embeddings
       lowerCamelCase		:	Dict							=      type_vocab_size
       lowerCamelCase		:	Dict							=      type_sequence_label_size
       lowerCamelCase		:	str							=      initializer_range
       lowerCamelCase		:	Tuple							=      num_labels
       lowerCamelCase		:	Union[str, Any]							=      scope
       lowerCamelCase		:	Optional[Any]							=      range_bbox
      def 						UpperCamelCase__							(      self      ):
       lowerCamelCase		:	List[Any]							=      ids_tensor([self.batch_size, self.seq_length]    ,  self.vocab_size      )

       lowerCamelCase		:	int							=      ids_tensor([self.batch_size, self.seq_length, 4]    ,  self.range_bbox      )
       # Ensure that bbox is legal
       for i in range(bbox.shape[0]      ):
        for j in range(bbox.shape[1]      ):
         if bbox[i, j, 3] < bbox[i, j, 1]:
          lowerCamelCase		:	int							=      bbox[i, j, 3]
          lowerCamelCase		:	Tuple							=      bbox[i, j, 1]
          lowerCamelCase		:	Optional[int]							=      t
         if bbox[i, j, 2] < bbox[i, j, 0]:
          lowerCamelCase		:	List[str]							=      bbox[i, j, 2]
          lowerCamelCase		:	Tuple							=      bbox[i, j, 0]
          lowerCamelCase		:	List[str]							=      t

       lowerCamelCase		:	Any							=      None
       if self.use_input_mask:
        lowerCamelCase		:	List[str]							=      ids_tensor([self.batch_size, self.seq_length]    ,  vocab_size=2      )

       lowerCamelCase		:	Tuple							=      None
       if self.use_token_type_ids:
        lowerCamelCase		:	Optional[Any]							=      ids_tensor([self.batch_size, self.seq_length]    ,  self.type_vocab_size      )

       lowerCamelCase		:	Tuple							=      None
       lowerCamelCase		:	int							=      None
       if self.use_labels:
        lowerCamelCase		:	Optional[int]							=      ids_tensor([self.batch_size]    ,  self.type_sequence_label_size      )
        lowerCamelCase		:	Any							=      ids_tensor([self.batch_size, self.seq_length]    ,  self.num_labels      )

       lowerCamelCase		:	Optional[int]							=      self.get_config()

       return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels
      def 						UpperCamelCase__							(      self      ):
       return LiltConfig(
           vocab_size=self.vocab_size    ,  hidden_size=self.hidden_size    ,  num_hidden_layers=self.num_hidden_layers    ,  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    ,  )
      def 						UpperCamelCase__							(      self    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__    ,  ):
       lowerCamelCase		:	List[str]							=      LiltModel(config=__magic_name__      )
       model.to(__magic_name__      )
       model.eval()
       lowerCamelCase		:	Union[str, Any]							=      model(__magic_name__    ,  bbox=__magic_name__    ,  attention_mask=__magic_name__    ,  token_type_ids=__magic_name__      )
       lowerCamelCase		:	List[Any]							=      model(__magic_name__    ,  bbox=__magic_name__    ,  token_type_ids=__magic_name__      )
       lowerCamelCase		:	List[Any]							=      model(__magic_name__    ,  bbox=__magic_name__      )

       self.parent.assertEqual(result.last_hidden_state.shape    ,  (self.batch_size, self.seq_length, self.hidden_size)      )
       self.parent.assertEqual(result.pooler_output.shape    ,  (self.batch_size, self.hidden_size)      )
      def 						UpperCamelCase__							(      self    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__    ,  ):
       lowerCamelCase		:	Union[str, Any]							=      self.num_labels
       lowerCamelCase		:	Any							=      LiltForTokenClassification(config=__magic_name__      )
       model.to(__magic_name__      )
       model.eval()
       lowerCamelCase		:	Optional[Any]							=      model(
           __magic_name__    ,  bbox=__magic_name__    ,  attention_mask=__magic_name__    ,  token_type_ids=__magic_name__    ,  labels=__magic_name__      )
       self.parent.assertEqual(result.logits.shape    ,  (self.batch_size, self.seq_length, self.num_labels)      )
      def 						UpperCamelCase__							(      self    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__    ,  ):
       lowerCamelCase		:	List[str]							=      LiltForQuestionAnswering(config=__magic_name__      )
       model.to(__magic_name__      )
       model.eval()
       lowerCamelCase		:	Optional[Any]							=      model(
           __magic_name__    ,  bbox=__magic_name__    ,  attention_mask=__magic_name__    ,  token_type_ids=__magic_name__    ,  start_positions=__magic_name__    ,  end_positions=__magic_name__    ,  )
       self.parent.assertEqual(result.start_logits.shape    ,  (self.batch_size, self.seq_length)      )
       self.parent.assertEqual(result.end_logits.shape    ,  (self.batch_size, self.seq_length)      )






      def 						UpperCamelCase__							(      self      ):
       lowerCamelCase		:	Any							=      self.prepare_config_and_inputs()
       (
           (
           lowerCamelCase
       )			,    (
           lowerCamelCase
       )			,    (
           lowerCamelCase
       )			,    (
           lowerCamelCase
       )			,    (
           lowerCamelCase
       )			,    (
           lowerCamelCase
       )			,    (
           lowerCamelCase
       )			,    
       )		:	Optional[int]							=      config_and_inputs
       lowerCamelCase		:	Dict							=      {
           """input_ids""": input_ids,
           """bbox""": bbox,
           """token_type_ids""": token_type_ids,
           """attention_mask""": input_mask,
       }
       return config, inputs_dict





@require_torch
class 							A__		(	__SCREAMING_SNAKE_CASE  ,   __SCREAMING_SNAKE_CASE  ,   __SCREAMING_SNAKE_CASE  ,   unittest.TestCase):
      _UpperCAmelCase				:    Optional[Any]           =			(
          (
              LiltModel,
              LiltForSequenceClassification,
              LiltForTokenClassification,
              LiltForQuestionAnswering,
          )
          if is_torch_available()
          else ()
      )
      _UpperCAmelCase				:    List[Any]           =			(
          {
              """feature-extraction""": LiltModel,
              """question-answering""": LiltForQuestionAnswering,
              """text-classification""": LiltForSequenceClassification,
              """token-classification""": LiltForTokenClassification,
              """zero-shot""": LiltForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      _UpperCAmelCase				:    Optional[int]           =			False
      _UpperCAmelCase				:    Dict           =			False
      def 						UpperCamelCase__							(      self    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__      ):
       return True
      def 						UpperCamelCase__							(      self      ):
       lowerCamelCase		:	Optional[Any]							=      LiltModelTester(self      )
       lowerCamelCase		:	int							=      ConfigTester(self    ,  config_class=__magic_name__    ,  hidden_size=3_7      )
      def 						UpperCamelCase__							(      self      ):
       self.config_tester.run_common_tests()
      def 						UpperCamelCase__							(      self      ):
       lowerCamelCase		:	Dict							=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__magic_name__      )
      def 						UpperCamelCase__							(      self      ):
       lowerCamelCase		:	int							=      self.model_tester.prepare_config_and_inputs()
       for type in ["absolute", "relative_key", "relative_key_query"]:
        lowerCamelCase		:	Tuple							=      type
        self.model_tester.create_and_check_model(*__magic_name__      )
      def 						UpperCamelCase__							(      self      ):
       lowerCamelCase		:	List[Any]							=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_token_classification(*__magic_name__      )
      def 						UpperCamelCase__							(      self      ):
       lowerCamelCase		:	List[str]							=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_question_answering(*__magic_name__      )






      @slow
      def 						UpperCamelCase__							(      self      ):
       for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowerCamelCase		:	str							=      LiltModel.from_pretrained(__magic_name__      )
        self.assertIsNotNone(__magic_name__      )





@require_torch
@slow
class 							A__		(	unittest.TestCase):
      def 						UpperCamelCase__							(      self      ):
       lowerCamelCase		:	Union[str, Any]							=      LiltModel.from_pretrained("""SCUT-DLVCLab/lilt-roberta-en-base"""      ).to(__magic_name__      )

       lowerCamelCase		:	Optional[Any]							=      torch.tensor([[1, 2]]    ,  device=__magic_name__      )
       lowerCamelCase		:	Optional[Any]							=      torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]]    ,  device=__magic_name__      )

       # forward pass
       with torch.no_grad():
        lowerCamelCase		:	int							=      model(input_ids=__magic_name__    ,  bbox=__magic_name__      )

       lowerCamelCase		:	Union[str, Any]							=      torch.Size([1, 2, 7_6_8]      )
       lowerCamelCase		:	Union[str, Any]							=      torch.tensor(
           [[-0.0_653, 0.0_950, -0.0_061], [-0.0_545, 0.0_926, -0.0_324]]    ,  device=__magic_name__    ,  )

       self.assertTrue(outputs.last_hidden_state.shape    ,  __magic_name__      )
       self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3]    ,  __magic_name__    ,  atol=1e-3      )      )






from scipy.stats import pearsonr

import datasets


_lowerCamelCase					   ="""
Pearson correlation coefficient and p-value for testing non-correlation.
The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.
The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.
"""


_lowerCamelCase					   ="""
Args:
    predictions (`list` of `int`): Predicted class labels, as returned by a model.
    references (`list` of `int`): Ground truth labels.
    return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.

Returns:
    pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.
    p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.

Examples:

    Example 1-A simple example using only predictions and references.
        >>> pearsonr_metric = datasets.load_metric(\"pearsonr\")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])
        >>> print(round(results['pearsonr'], 2))
        -0.74

    Example 2-The same as Example 1, but that also returns the `p-value`.
        >>> pearsonr_metric = datasets.load_metric(\"pearsonr\")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)
        >>> print(sorted(list(results.keys())))
        ['p-value', 'pearsonr']
        >>> print(round(results['pearsonr'], 2))
        -0.74
        >>> print(round(results['p-value'], 2))
        0.15
"""


_lowerCamelCase					   ="""
@article{2020SciPy-NMeth,
author  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
      Haberland, Matt and Reddy, Tyler and Cournapeau, David and
      Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
      Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
      Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
      Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
      Kern, Robert and Larson, Eric and Carey, C J and
      Polat, Ilhan and Feng, Yu and Moore, Eric W. and
      {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
      Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
      Harris, Charles R. and Archibald, Anne M. and
      Ribeiro, Antonio H. and Pedregosa, Fabian and
      {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
title   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
      Computing in Python}},
journal = {Nature Methods},
year    = {2020},
volume  = {17},
pages   = {261--272},
adsurl  = {https://rdcu.be/b08Wh},
doi = {10.1038/s41592-019-0686-2},
}
"""





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION  ,   _KWARGS_DESCRIPTION)
class 							A__		(	datasets.Metric):
      def 						UpperCamelCase__							(      self      ):
       return datasets.MetricInfo(
           description=_DESCRIPTION    ,  citation=_CITATION    ,  inputs_description=_KWARGS_DESCRIPTION    ,  features=datasets.Features(
               {
                   """predictions""": datasets.Value("""float"""      ),
                   """references""": datasets.Value("""float"""      ),
               }      )    ,  reference_urls=["""https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html"""]    ,  )






      def 						UpperCamelCase__							(      self    ,  __magic_name__    ,  __magic_name__    ,  __magic_name__=False      ):
       if return_pvalue:
        lowerCamelCase		:	Optional[Any]							=      pearsonr(__magic_name__    ,  __magic_name__      )
        return {"pearsonr": results[0], "p-value": results[1]}
       else:
        return {"pearsonr": float(pearsonr(__magic_name__    ,  __magic_name__      )[0]      )}




