






'''simple docstring'''
import unittest

from transformers import TrOCRConfig
from transformers.testing_utils import is_torch_available, require_torch, 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.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM






@require_torch
class        __SCREAMING_SNAKE_CASE :




 def __init__( self		:							List[Any]   , __lowercase		:							List[str]   , __lowercase		:							Dict=99   , __lowercase		:							Dict=13   , __lowercase		:							List[Any]=16   , __lowercase		:							Union[str, Any]=7   , __lowercase		:							str=True   , __lowercase		:							Optional[Any]=True   , __lowercase		:							int=True   , __lowercase		:							int=False   , __lowercase		:							int=True   , __lowercase		:							List[str]=2   , __lowercase		:							Dict=32   , __lowercase		:							Dict=4   , __lowercase		:							Optional[int]=4   , __lowercase		:							Dict=30   , __lowercase		:							List[str]=0   , __lowercase		:							Dict=1   , __lowercase		:							List[Any]=2   , __lowercase		:							int=None   , )		->  Optional[Any]:
       SCREAMING_SNAKE_CASE__       :			List[str]													=parent
       SCREAMING_SNAKE_CASE__       :			Any													=batch_size
       SCREAMING_SNAKE_CASE__       :			List[str]													=decoder_seq_length
       # For common tests
       SCREAMING_SNAKE_CASE__       :			List[str]													=self.decoder_seq_length
       SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=is_training
       SCREAMING_SNAKE_CASE__       :			Any													=use_attention_mask
       SCREAMING_SNAKE_CASE__       :			Tuple													=use_labels

       SCREAMING_SNAKE_CASE__       :			Optional[Any]													=vocab_size
       SCREAMING_SNAKE_CASE__       :			Any													=d_model
       SCREAMING_SNAKE_CASE__       :			Tuple													=d_model
       SCREAMING_SNAKE_CASE__       :			str													=decoder_layers
       SCREAMING_SNAKE_CASE__       :			Dict													=decoder_layers
       SCREAMING_SNAKE_CASE__       :			Optional[Any]													=decoder_ffn_dim
       SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=decoder_attention_heads
       SCREAMING_SNAKE_CASE__       :			Optional[int]													=decoder_attention_heads
       SCREAMING_SNAKE_CASE__       :			str													=eos_token_id
       SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=bos_token_id
       SCREAMING_SNAKE_CASE__       :			List[str]													=pad_token_id
       SCREAMING_SNAKE_CASE__       :			Dict													=decoder_start_token_id
       SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=use_cache
       SCREAMING_SNAKE_CASE__       :			Any													=max_position_embeddings

       SCREAMING_SNAKE_CASE__       :			Dict													=None
       SCREAMING_SNAKE_CASE__       :			List[Any]													=decoder_seq_length
       SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=2
       SCREAMING_SNAKE_CASE__       :			Optional[Any]													=1




 def        __magic_name__		( self		:							int )		->  Union[str, Any]:
       SCREAMING_SNAKE_CASE__       :			Dict													=ids_tensor([self.batch_size, self.decoder_seq_length]   , self.vocab_size )

       SCREAMING_SNAKE_CASE__       :			Optional[Any]													=None
       if self.use_attention_mask:
             SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=ids_tensor([self.batch_size, self.decoder_seq_length]   , vocab_size=2 )

       SCREAMING_SNAKE_CASE__       :			Any													=None
       if self.use_labels:
             SCREAMING_SNAKE_CASE__       :			List[str]													=ids_tensor([self.batch_size, self.decoder_seq_length]   , self.vocab_size )

       SCREAMING_SNAKE_CASE__       :			int													=TrOCRConfig(
           vocab_size=self.vocab_size   , d_model=self.d_model   , decoder_layers=self.decoder_layers   , decoder_ffn_dim=self.decoder_ffn_dim   , decoder_attention_heads=self.decoder_attention_heads   , eos_token_id=self.eos_token_id   , bos_token_id=self.bos_token_id   , use_cache=self.use_cache   , pad_token_id=self.pad_token_id   , decoder_start_token_id=self.decoder_start_token_id   , max_position_embeddings=self.max_position_embeddings   , )

       return (config, input_ids, attention_mask, lm_labels)




 def        __magic_name__		( self		:							List[Any]   , __lowercase		:							str   , __lowercase		:							Dict   , __lowercase		:							Any   , __lowercase		:							str   , )		->  Optional[int]:
       SCREAMING_SNAKE_CASE__       :			Any													=True
       SCREAMING_SNAKE_CASE__       :			Tuple													=TrOCRDecoder(config=__lowercase ).to(__lowercase ).eval()
       SCREAMING_SNAKE_CASE__       :			Tuple													=input_ids[:2]

       input_ids[input_ids == 0] += 1
       # first forward pass
       SCREAMING_SNAKE_CASE__       :			Optional[int]													=model(__lowercase   , use_cache=__lowercase )
       SCREAMING_SNAKE_CASE__       :			Optional[int]													=model(__lowercase )
       SCREAMING_SNAKE_CASE__       :			int													=model(__lowercase   , use_cache=__lowercase )

       self.parent.assertTrue(len(__lowercase ) == len(__lowercase ) )
       self.parent.assertTrue(len(__lowercase ) == len(__lowercase ) + 1 )

       SCREAMING_SNAKE_CASE__       :			Any													=outputs['''past_key_values''']

       # create hypothetical next token and extent to next_input_ids
       SCREAMING_SNAKE_CASE__       :			Dict													=ids_tensor((2, 1)   , config.vocab_size - 1 ) + 1

       # append to next input_ids and
       SCREAMING_SNAKE_CASE__       :			int													=torch.cat([input_ids, next_tokens]   , dim=-1 )

       SCREAMING_SNAKE_CASE__       :			List[Any]													=model(__lowercase )['''last_hidden_state''']
       SCREAMING_SNAKE_CASE__       :			int													=model(__lowercase   , past_key_values=__lowercase )['''last_hidden_state''']

       # select random slice
       SCREAMING_SNAKE_CASE__       :			Optional[Any]													=ids_tensor((1,)   , output_from_past.shape[-1] ).item()
       SCREAMING_SNAKE_CASE__       :			Tuple													=output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
       SCREAMING_SNAKE_CASE__       :			List[Any]													=output_from_past[:, 0, random_slice_idx].detach()

       # test that outputs are equal for slice
       assert torch.allclose(__lowercase   , __lowercase   , atol=1e-3 )




 def        __magic_name__		( self		:							Optional[Any] )		->  str:
       SCREAMING_SNAKE_CASE__       :			Optional[Any]													=self.prepare_config_and_inputs()
       SCREAMING_SNAKE_CASE__						,		SCREAMING_SNAKE_CASE__						,		SCREAMING_SNAKE_CASE__						,		SCREAMING_SNAKE_CASE__       :			str													=config_and_inputs

       SCREAMING_SNAKE_CASE__       :			Optional[int]													={'''input_ids''': input_ids, '''attention_mask''': attention_mask}
       return config, inputs_dict






@require_torch
class        __SCREAMING_SNAKE_CASE (     lowerCamelCase		,			lowerCamelCase		,			lowerCamelCase		,			unittest.TestCase			):
 snake_case_												=							(TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
 snake_case_												=							(TrOCRForCausalLM,) if is_torch_available() else ()
 snake_case_												=							{"""text-generation""": TrOCRForCausalLM} if is_torch_available() else {}
 snake_case_												=							True
 snake_case_												=							False




 def        __magic_name__		( self		:							List[str] )		->  str:
       SCREAMING_SNAKE_CASE__       :			Optional[int]													=TrOCRStandaloneDecoderModelTester(self   , is_training=__lowercase )
       SCREAMING_SNAKE_CASE__       :			int													=ConfigTester(self   , config_class=__lowercase )




 def        __magic_name__		( self		:							Tuple )		->  Tuple:
       pass




 def        __magic_name__		( self		:							int )		->  List[Any]:
       pass




 def        __magic_name__		( self		:							int )		->  Tuple:
       pass




 def        __magic_name__		( self		:							List[str] )		->  Optional[Any]:
       self.config_tester.run_common_tests()




 def        __magic_name__		( self		:							Any )		->  Dict:
       SCREAMING_SNAKE_CASE__       :			Optional[int]													=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_decoder_model_past(*__lowercase )




 def        __magic_name__		( self		:							Union[str, Any] )		->  Optional[int]:
       return




 @unittest.skip('''The model doesn\'t support left padding''' )  # and it's not used enough to be worth fixing :)
 def        __magic_name__		( self		:							str )		->  str:
       pass







'''simple docstring'''
from scipy.stats import pearsonr

import datasets


a_					=	'\nPearson correlation coefficient and p-value for testing non-correlation.\nThe 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.\nThe 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.\n'


a_					=	'\nArgs:\n    predictions (`list` of `int`): Predicted class labels, as returned by a model.\n    references (`list` of `int`): Ground truth labels.\n    return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n    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.\n    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.\n\nExamples:\n\n    Example 1-A simple example using only predictions and references.\n        >>> pearsonr_metric = datasets.load_metric("pearsonr")\n        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n        >>> print(round(results[\'pearsonr\'], 2))\n        -0.74\n\n    Example 2-The same as Example 1, but that also returns the `p-value`.\n        >>> pearsonr_metric = datasets.load_metric("pearsonr")\n        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n        >>> print(sorted(list(results.keys())))\n        [\'p-value\', \'pearsonr\']\n        >>> print(round(results[\'pearsonr\'], 2))\n        -0.74\n        >>> print(round(results[\'p-value\'], 2))\n        0.15\n'


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






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION		,			_KWARGS_DESCRIPTION			)
class        __SCREAMING_SNAKE_CASE (     datasets.Metric			):




 def        __magic_name__		( self		:							List[Any] )		->  Any:
       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        __magic_name__		( self		:							Optional[int]   , __lowercase		:							List[Any]   , __lowercase		:							List[Any]   , __lowercase		:							str=False )		->  int:
       if return_pvalue:
             SCREAMING_SNAKE_CASE__       :			List[str]													=pearsonr(__lowercase   , __lowercase )
             return {"pearsonr": results[0], "p-value": results[1]}
       else:
             return {"pearsonr": float(pearsonr(__lowercase   , __lowercase )[0] )}