



'''simple docstring'''





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    :



 '''simple docstring'''







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


      """simple docstring"""



      _a											=						parent
      _a											=						batch_size
      _a											=						seq_length
      _a											=						is_training
      _a											=						use_input_mask
      _a											=						use_token_type_ids
      _a											=						use_labels
      _a											=						vocab_size
      _a											=						hidden_size
      _a											=						num_hidden_layers
      _a											=						num_attention_heads
      _a											=						intermediate_size
      _a											=						hidden_act
      _a											=						hidden_dropout_prob
      _a											=						attention_probs_dropout_prob
      _a											=						max_position_embeddings
      _a											=						type_vocab_size
      _a											=						type_sequence_label_size
      _a											=						initializer_range
      _a											=						num_labels
      _a											=						scope
      _a											=						range_bbox



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


      """simple docstring"""



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

      _a											=						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]:
                     _a											=						bbox[i, j, 3]
                     _a											=						bbox[i, j, 1]
                     _a											=						t
                if bbox[i, j, 2] < bbox[i, j, 0]:
                     _a											=						bbox[i, j, 2]
                     _a											=						bbox[i, j, 0]
                     _a											=						t

      _a											=						None
      if self.use_input_mask:
           _a											=						ids_tensor([self.batch_size, self.seq_length]				,     vocab_size=2 )

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

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

      _a											=						self.get_config()

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



 def       a__						(self )					->  str:


      """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       a__						(self				,     A				,     A				,     A				,     A				,     A				,     A				,     A				,     )					->  List[str]:


      """simple docstring"""



      _a											=						LiltModel(config=A_ )
      model.to(A_ )
      model.eval()
      _a											=						model(A_				,     bbox=A_				,     attention_mask=A_				,     token_type_ids=A_ )
      _a											=						model(A_				,     bbox=A_				,     token_type_ids=A_ )
      _a											=						model(A_				,     bbox=A_ )

      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       a__						(self				,     A				,     A				,     A				,     A				,     A				,     A				,     A				,     )					->  Optional[Any]:


      """simple docstring"""



      _a											=						self.num_labels
      _a											=						LiltForTokenClassification(config=A_ )
      model.to(A_ )
      model.eval()
      _a											=						model(
          A_				,     bbox=A_				,     attention_mask=A_				,     token_type_ids=A_				,     labels=A_ )
      self.parent.assertEqual(result.logits.shape				,     (self.batch_size, self.seq_length, self.num_labels) )



 def       a__						(self				,     A				,     A				,     A				,     A				,     A				,     A				,     A				,     )					->  List[Any]:


      """simple docstring"""



      _a											=						LiltForQuestionAnswering(config=A_ )
      model.to(A_ )
      model.eval()
      _a											=						model(
          A_				,     bbox=A_				,     attention_mask=A_				,     token_type_ids=A_				,     start_positions=A_				,     end_positions=A_				,     )
      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       a__						(self )					->  List[Any]:


      """simple docstring"""



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






@require_torch
class __A    (						_lowercase     ,     _lowercase     ,     _lowercase     ,     unittest.TestCase		):



 '''simple docstring'''







 __lowerCamelCase					: Union[str, Any]    = (
     (
         LiltModel,
         LiltForSequenceClassification,
         LiltForTokenClassification,
         LiltForQuestionAnswering,
     )
     if is_torch_available()
     else ()
 )
 __lowerCamelCase					: str    = (
     {
         '''feature-extraction''': LiltModel,
         '''question-answering''': LiltForQuestionAnswering,
         '''text-classification''': LiltForSequenceClassification,
         '''token-classification''': LiltForTokenClassification,
         '''zero-shot''': LiltForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )
 __lowerCamelCase					: Optional[Any]    = False
 __lowerCamelCase					: List[str]    = False



 def       a__						(self				,     A				,     A				,     A				,     A				,     A )					->  int:


      """simple docstring"""



      return True



 def       a__						(self )					->  Optional[int]:


      """simple docstring"""



      _a											=						LiltModelTester(self )
      _a											=						ConfigTester(self				,     config_class=A_				,     hidden_size=37 )



 def       a__						(self )					->  Optional[int]:


      """simple docstring"""



      self.config_tester.run_common_tests()



 def       a__						(self )					->  Any:


      """simple docstring"""



      _a											=						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*A_ )



 def       a__						(self )					->  Tuple:


      """simple docstring"""



      _a											=						self.model_tester.prepare_config_and_inputs()
      for type in ["absolute", "relative_key", "relative_key_query"]:
           _a											=						type
           self.model_tester.create_and_check_model(*A_ )



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


      """simple docstring"""



      _a											=						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_token_classification(*A_ )



 def       a__						(self )					->  Any:


      """simple docstring"""



      _a											=						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_question_answering(*A_ )



 @slow
 def       a__						(self )					->  List[Any]:


      """simple docstring"""



      for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           _a											=						LiltModel.from_pretrained(A_ )
           self.assertIsNotNone(A_ )






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



 '''simple docstring'''







 def       a__						(self )					->  int:


      """simple docstring"""



      _a											=						LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''' ).to(A_ )

      _a											=						torch.tensor([[1, 2]]				,     device=A_ )
      _a											=						torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]]				,     device=A_ )

      # forward pass
      with torch.no_grad():
           _a											=						model(input_ids=A_				,     bbox=A_ )

      _a											=						torch.Size([1, 2, 768] )
      _a											=						torch.tensor(
          [[-0.0653, 0.0950, -0.0061], [-0.0545, 0.0926, -0.0324]]				,     device=A_				,     )

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








'''simple docstring'''





import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
  import torch

if is_vision_available():
  from PIL import Image

  from transformers import MobileNetVaImageProcessor






class __A    (						unittest.TestCase		):



 '''simple docstring'''







 def __init__(self				,     A				,     A=7				,     A=3				,     A=18				,     A=30				,     A=400				,     A=True				,     A=None				,     A=True				,     A=None				,     )					->  Any:


      """simple docstring"""



      _a											=						size if size is not None else {'''shortest_edge''': 20}
      _a											=						crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}
      _a											=						parent
      _a											=						batch_size
      _a											=						num_channels
      _a											=						image_size
      _a											=						min_resolution
      _a											=						max_resolution
      _a											=						do_resize
      _a											=						size
      _a											=						do_center_crop
      _a											=						crop_size



 def       a__						(self )					->  Optional[Any]:


      """simple docstring"""



      return {
          "do_resize": self.do_resize,
          "size": self.size,
          "do_center_crop": self.do_center_crop,
          "crop_size": self.crop_size,
      }






@require_torch
@require_vision
class __A    (						A     ,     unittest.TestCase		):



 '''simple docstring'''







 __lowerCamelCase					: Tuple    = MobileNetVaImageProcessor if is_vision_available() else None



 def       a__						(self )					->  int:


      """simple docstring"""



      _a											=						MobileNetVaImageProcessingTester(self )



 @property
 def       a__						(self )					->  Optional[Any]:


      """simple docstring"""



      return self.image_processor_tester.prepare_image_processor_dict()



 def       a__						(self )					->  str:


      """simple docstring"""



      _a											=						self.image_processing_class(**self.image_processor_dict )
      self.assertTrue(hasattr(A				,     '''do_resize''' ) )
      self.assertTrue(hasattr(A				,     '''size''' ) )
      self.assertTrue(hasattr(A				,     '''do_center_crop''' ) )
      self.assertTrue(hasattr(A				,     '''crop_size''' ) )



 def       a__						(self )					->  Optional[int]:


      """simple docstring"""



      _a											=						self.image_processing_class.from_dict(self.image_processor_dict )
      self.assertEqual(image_processor.size				,     {'''shortest_edge''': 20} )
      self.assertEqual(image_processor.crop_size				,     {'''height''': 18, '''width''': 18} )

      _a											=						self.image_processing_class.from_dict(self.image_processor_dict				,     size=42				,     crop_size=84 )
      self.assertEqual(image_processor.size				,     {'''shortest_edge''': 42} )
      self.assertEqual(image_processor.crop_size				,     {'''height''': 84, '''width''': 84} )



 def       a__						(self )					->  Union[str, Any]:


      """simple docstring"""



      pass



 def       a__						(self )					->  Any:


      """simple docstring"""



      _a											=						self.image_processing_class(**self.image_processor_dict )
      # create random PIL images
      _a											=						prepare_image_inputs(self.image_processor_tester				,     equal_resolution=A )
      for image in image_inputs:
           self.assertIsInstance(A				,     Image.Image )

      # Test not batched input
      _a											=						image_processing(image_inputs[0]				,     return_tensors='''pt''' ).pixel_values
      self.assertEqual(
          encoded_images.shape				,     (
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['''height'''],
              self.image_processor_tester.crop_size['''width'''],
          )				,     )

      # Test batched
      _a											=						image_processing(A				,     return_tensors='''pt''' ).pixel_values
      self.assertEqual(
          encoded_images.shape				,     (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['''height'''],
              self.image_processor_tester.crop_size['''width'''],
          )				,     )



 def       a__						(self )					->  Optional[int]:


      """simple docstring"""



      _a											=						self.image_processing_class(**self.image_processor_dict )
      # create random numpy tensors
      _a											=						prepare_image_inputs(self.image_processor_tester				,     equal_resolution=A				,     numpify=A )
      for image in image_inputs:
           self.assertIsInstance(A				,     np.ndarray )

      # Test not batched input
      _a											=						image_processing(image_inputs[0]				,     return_tensors='''pt''' ).pixel_values
      self.assertEqual(
          encoded_images.shape				,     (
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['''height'''],
              self.image_processor_tester.crop_size['''width'''],
          )				,     )

      # Test batched
      _a											=						image_processing(A				,     return_tensors='''pt''' ).pixel_values
      self.assertEqual(
          encoded_images.shape				,     (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['''height'''],
              self.image_processor_tester.crop_size['''width'''],
          )				,     )



 def       a__						(self )					->  Optional[Any]:


      """simple docstring"""



      _a											=						self.image_processing_class(**self.image_processor_dict )
      # create random PyTorch tensors
      _a											=						prepare_image_inputs(self.image_processor_tester				,     equal_resolution=A				,     torchify=A )
      for image in image_inputs:
           self.assertIsInstance(A				,     torch.Tensor )

      # Test not batched input
      _a											=						image_processing(image_inputs[0]				,     return_tensors='''pt''' ).pixel_values
      self.assertEqual(
          encoded_images.shape				,     (
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['''height'''],
              self.image_processor_tester.crop_size['''width'''],
          )				,     )

      # Test batched
      _a											=						image_processing(A				,     return_tensors='''pt''' ).pixel_values
      self.assertEqual(
          encoded_images.shape				,     (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['''height'''],
              self.image_processor_tester.crop_size['''width'''],
          )				,     )



