





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    _SCREAMING_SNAKE_CASE						:







 '''simple docstring'''

 def __init__(self				:   Optional[int]       , UpperCAmelCase_				:   Tuple       , UpperCAmelCase_				:   str=13       , UpperCAmelCase_				:   str=7       , UpperCAmelCase_				:   str=True       , UpperCAmelCase_				:   Union[str, Any]=True       , UpperCAmelCase_				:   List[str]=True       , UpperCAmelCase_				:   Tuple=True       , UpperCAmelCase_				:   List[Any]=99       , UpperCAmelCase_				:   Union[str, Any]=24       , UpperCAmelCase_				:   int=2       , UpperCAmelCase_				:   List[Any]=6       , UpperCAmelCase_				:   Tuple=37       , UpperCAmelCase_				:   Tuple="gelu"       , UpperCAmelCase_				:   Dict=0.1       , UpperCAmelCase_				:   Union[str, Any]=0.1       , UpperCAmelCase_				:   Tuple=512       , UpperCAmelCase_				:   Union[str, Any]=16       , UpperCAmelCase_				:   List[Any]=2       , UpperCAmelCase_				:   Tuple=0.02       , UpperCAmelCase_				:   Optional[int]=3       , UpperCAmelCase_				:   Tuple=None       , UpperCAmelCase_				:   int=1_000       , )       ->int:



   '''simple docstring'''



   lowerCamelCase__:      List[Any]			  =parent
   lowerCamelCase__:      Any			  =batch_size
   lowerCamelCase__:      Optional[int]			  =seq_length
   lowerCamelCase__:      Any			  =is_training
   lowerCamelCase__:      Any			  =use_input_mask
   lowerCamelCase__:      Optional[Any]			  =use_token_type_ids
   lowerCamelCase__:      Optional[int]			  =use_labels
   lowerCamelCase__:      str			  =vocab_size
   lowerCamelCase__:      Dict			  =hidden_size
   lowerCamelCase__:      str			  =num_hidden_layers
   lowerCamelCase__:      List[Any]			  =num_attention_heads
   lowerCamelCase__:      Any			  =intermediate_size
   lowerCamelCase__:      Any			  =hidden_act
   lowerCamelCase__:      Optional[int]			  =hidden_dropout_prob
   lowerCamelCase__:      List[Any]			  =attention_probs_dropout_prob
   lowerCamelCase__:      Optional[Any]			  =max_position_embeddings
   lowerCamelCase__:      int			  =type_vocab_size
   lowerCamelCase__:      int			  =type_sequence_label_size
   lowerCamelCase__:      int			  =initializer_range
   lowerCamelCase__:      Optional[int]			  =num_labels
   lowerCamelCase__:      Optional[int]			  =scope
   lowerCamelCase__:      Dict			  =range_bbox

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



   '''simple docstring'''



   lowerCamelCase__:      Optional[int]			  =ids_tensor([self.batch_size, self.seq_length]       , self.vocab_size)

   lowerCamelCase__:      Optional[Any]			  =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__:      Any			  =bbox[i, j, 3]
         lowerCamelCase__:      Any			  =bbox[i, j, 1]
         lowerCamelCase__:      List[str]			  =t
       if bbox[i, j, 2] < bbox[i, j, 0]:
         lowerCamelCase__:      Dict			  =bbox[i, j, 2]
         lowerCamelCase__:      Any			  =bbox[i, j, 0]
         lowerCamelCase__:      Any			  =t

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

   lowerCamelCase__:      List[str]			  =None
   if self.use_token_type_ids:
     lowerCamelCase__:      List[str]			  =ids_tensor([self.batch_size, self.seq_length]       , self.type_vocab_size)

   lowerCamelCase__:      Dict			  =None
   lowerCamelCase__:      List[Any]			  =None
   if self.use_labels:
     lowerCamelCase__:      Union[str, Any]			  =ids_tensor([self.batch_size]       , self.type_sequence_label_size)
     lowerCamelCase__:      str			  =ids_tensor([self.batch_size, self.seq_length]       , self.num_labels)

   lowerCamelCase__:      List[Any]			  =self.get_config()

   return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels

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



   '''simple docstring'''



   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 							SCREAMING_SNAKE_CASE_					(self				:   Any       , UpperCAmelCase_				:   Optional[int]       , UpperCAmelCase_				:   List[str]       , UpperCAmelCase_				:   Any       , UpperCAmelCase_				:   int       , UpperCAmelCase_				:   List[str]       , UpperCAmelCase_				:   List[str]       , UpperCAmelCase_				:   Union[str, Any]       , )       ->Dict:



   '''simple docstring'''



   lowerCamelCase__:      Any			  =LiltModel(config=UpperCAmelCase_)
   model.to(UpperCAmelCase_)
   model.eval()
   lowerCamelCase__:      List[Any]			  =model(UpperCAmelCase_       , bbox=UpperCAmelCase_       , attention_mask=UpperCAmelCase_       , token_type_ids=UpperCAmelCase_)
   lowerCamelCase__:      int			  =model(UpperCAmelCase_       , bbox=UpperCAmelCase_       , token_type_ids=UpperCAmelCase_)
   lowerCamelCase__:      Optional[Any]			  =model(UpperCAmelCase_       , bbox=UpperCAmelCase_)

   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 							SCREAMING_SNAKE_CASE_					(self				:   Optional[int]       , UpperCAmelCase_				:   Tuple       , UpperCAmelCase_				:   List[str]       , UpperCAmelCase_				:   Dict       , UpperCAmelCase_				:   Optional[Any]       , UpperCAmelCase_				:   Dict       , UpperCAmelCase_				:   Dict       , UpperCAmelCase_				:   Tuple       , )       ->Any:



   '''simple docstring'''



   lowerCamelCase__:      str			  =self.num_labels
   lowerCamelCase__:      Optional[int]			  =LiltForTokenClassification(config=UpperCAmelCase_)
   model.to(UpperCAmelCase_)
   model.eval()
   lowerCamelCase__:      Tuple			  =model(
       UpperCAmelCase_       , bbox=UpperCAmelCase_       , attention_mask=UpperCAmelCase_       , token_type_ids=UpperCAmelCase_       , labels=UpperCAmelCase_)
   self.parent.assertEqual(result.logits.shape       , (self.batch_size, self.seq_length, self.num_labels))

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



   '''simple docstring'''



   lowerCamelCase__:      Optional[Any]			  =LiltForQuestionAnswering(config=UpperCAmelCase_)
   model.to(UpperCAmelCase_)
   model.eval()
   lowerCamelCase__:      Tuple			  =model(
       UpperCAmelCase_       , bbox=UpperCAmelCase_       , attention_mask=UpperCAmelCase_       , token_type_ids=UpperCAmelCase_       , start_positions=UpperCAmelCase_       , end_positions=UpperCAmelCase_       , )
   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 							SCREAMING_SNAKE_CASE_					(self				:   Optional[Any])       ->List[str]:



   '''simple docstring'''



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



@require_torch
class    _SCREAMING_SNAKE_CASE						(	__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							unittest.TestCase    ):







 '''simple docstring'''
 lowercase_		=			(
     (
         LiltModel,
         LiltForSequenceClassification,
         LiltForTokenClassification,
         LiltForQuestionAnswering,
     )
     if is_torch_available()
     else ()
 )
 lowercase_		=			(
     {
         "feature-extraction": LiltModel,
         "question-answering": LiltForQuestionAnswering,
         "text-classification": LiltForSequenceClassification,
         "token-classification": LiltForTokenClassification,
         "zero-shot": LiltForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )
 lowercase_		=			False
 lowercase_		=			False

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



   '''simple docstring'''



   return True

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



   '''simple docstring'''



   lowerCamelCase__:      Union[str, Any]			  =LiltModelTester(self)
   lowerCamelCase__:      int			  =ConfigTester(self       , config_class=UpperCAmelCase_       , hidden_size=37)

 def 							SCREAMING_SNAKE_CASE_					(self				:   str)       ->List[str]:



   '''simple docstring'''



   self.config_tester.run_common_tests()

 def 							SCREAMING_SNAKE_CASE_					(self				:   Dict)       ->Optional[Any]:



   '''simple docstring'''



   lowerCamelCase__:      List[Any]			  =self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*UpperCAmelCase_)

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



   '''simple docstring'''



   lowerCamelCase__:      str			  =self.model_tester.prepare_config_and_inputs()
   for type in ["absolute", "relative_key", "relative_key_query"]:
     lowerCamelCase__:      int			  =type
     self.model_tester.create_and_check_model(*UpperCAmelCase_)

 def 							SCREAMING_SNAKE_CASE_					(self				:   Dict)       ->Optional[Any]:



   '''simple docstring'''



   lowerCamelCase__:      Union[str, Any]			  =self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase_)

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



   '''simple docstring'''



   lowerCamelCase__:      int			  =self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase_)







 @slow
 def 							SCREAMING_SNAKE_CASE_					(self				:   str)       ->Tuple:



   '''simple docstring'''



   for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     lowerCamelCase__:      int			  =LiltModel.from_pretrained(UpperCAmelCase_)
     self.assertIsNotNone(UpperCAmelCase_)



@require_torch
@slow
class    _SCREAMING_SNAKE_CASE						(	unittest.TestCase    ):







 '''simple docstring'''

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



   '''simple docstring'''



   lowerCamelCase__:      str			  =LiltModel.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base").to(UpperCAmelCase_)

   lowerCamelCase__:      Optional[Any]			  =torch.tensor([[1, 2]]       , device=UpperCAmelCase_)
   lowerCamelCase__:      Union[str, Any]			  =torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]]       , device=UpperCAmelCase_)

   # forward pass
   with torch.no_grad():
     lowerCamelCase__:      Optional[Any]			  =model(input_ids=UpperCAmelCase_       , bbox=UpperCAmelCase_)

   lowerCamelCase__:      Union[str, Any]			  =torch.Size([1, 2, 768])
   lowerCamelCase__:      List[str]			  =torch.tensor(
       [[-0.0653, 0.0950, -0.0061], [-0.0545, 0.0926, -0.0324]]       , device=UpperCAmelCase_       , )

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





'''simple docstring'''






from sklearn.metrics import recall_score

import datasets


__A					:  Dict											=      "\nRecall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:\nRecall = TP / (TP + FN)\nWhere TP is the true positives and FN is the false negatives.\n"


__A					:  List[Any]											=      "\nArgs:\n- **predictions** (`list` of `int`): The predicted labels.\n- **references** (`list` of `int`): The ground truth labels.\n- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None.\n- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.\n- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n    - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.\n    - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.\n    - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n    - `'weighted'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall.\n    - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.\n- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .\n    - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.\n    - `0`: If there is a zero division, the return value is `0`.\n    - `1`: If there is a zero division, the return value is `1`.\n\nReturns:\n- **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better.\n\nExamples:\n\n    Example 1-A simple example with some errors\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])\n        >>> print(results)\n        {'recall': 0.6666666666666666}\n\n    Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)\n        >>> print(results)\n        {'recall': 0.5}\n\n    Example 3-The same example as Example 1, but with `sample_weight` included.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)\n        >>> print(results)\n        {'recall': 0.55}\n\n    Example 4-A multiclass example, using different averages.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print(results)\n        {'recall': array([1., 0., 0.])}\n"


__A					:  str											=      "\n@article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011}\n"






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







    """simple docstring"""



    def __lowercase   (   self    :  str		)   ->  Dict:
      return datasets.MetricInfo(
          description=_DESCRIPTION    ,						citation=_CITATION    ,						inputs_description=_KWARGS_DESCRIPTION    ,						features=datasets.Features(
              {
                  """predictions""": datasets.Sequence(datasets.Value("""int32"""		)		),
                  """references""": datasets.Sequence(datasets.Value("""int32"""		)		),
              }
              if self.config_name == """multilabel"""
              else {
                  """predictions""": datasets.Value("""int32"""		),
                  """references""": datasets.Value("""int32"""		),
              }		)    ,						reference_urls=["""https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html"""]    ,						)





    def __lowercase   (   self    :  Tuple    ,						lowerCamelCase    :  Optional[Any]    ,						lowerCamelCase    :  str    ,						lowerCamelCase    :  Optional[Any]=None    ,						lowerCamelCase    :  Optional[int]=1    ,						lowerCamelCase    :  Union[str, Any]="binary"    ,						lowerCamelCase    :  Any=None    ,						lowerCamelCase    :  str="warn"    ,						)   ->  List[Any]:
      lowerCAmelCase_			:      Optional[int]			=   recall_score(
          lowerCamelCase    ,						lowerCamelCase    ,						labels=lowerCamelCase    ,						pos_label=lowerCamelCase    ,						average=lowerCamelCase    ,						sample_weight=lowerCamelCase    ,						zero_division=lowerCamelCase    ,						)
      return {"recall": float(lowerCamelCase		) if score.size == 1 else score}



