




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

			"""simple docstring"""







			def __init__(      self			,						lowerCamelCase__			,						lowerCamelCase__=13			,						lowerCamelCase__=7			,						lowerCamelCase__=True			,						lowerCamelCase__=True			,						lowerCamelCase__=True			,						lowerCamelCase__=True			,						lowerCamelCase__=99			,						lowerCamelCase__=24			,						lowerCamelCase__=2			,						lowerCamelCase__=6			,						lowerCamelCase__=37			,						lowerCamelCase__="gelu"			,						lowerCamelCase__=0.1			,						lowerCamelCase__=0.1			,						lowerCamelCase__=512			,						lowerCamelCase__=16			,						lowerCamelCase__=2			,						lowerCamelCase__=0.02			,						lowerCamelCase__=3			,						lowerCamelCase__=None			,						lowerCamelCase__=1_000			,						)    ->      Tuple:



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


			def       lowercase_    (      self							)    ->      Any:



							'''simple docstring'''
							__lowerCamelCase		       =    ids_tensor([self.batch_size, self.seq_length]			,						self.vocab_size							)

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

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

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

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

							__lowerCamelCase		       =    self.get_config()

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


			def       lowercase_    (      self							)    ->      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       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						)    ->      List[str]:



							'''simple docstring'''
							__lowerCamelCase		       =    LiltModel(config=lowerCamelCase__							)
							model.to(lowerCamelCase__							)
							model.eval()
							__lowerCamelCase		       =    model(lowerCamelCase__			,						bbox=lowerCamelCase__			,						attention_mask=lowerCamelCase__			,						token_type_ids=lowerCamelCase__							)
							__lowerCamelCase		       =    model(lowerCamelCase__			,						bbox=lowerCamelCase__			,						token_type_ids=lowerCamelCase__							)
							__lowerCamelCase		       =    model(lowerCamelCase__			,						bbox=lowerCamelCase__							)

							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       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						)    ->      int:



							'''simple docstring'''
							__lowerCamelCase		       =    self.num_labels
							__lowerCamelCase		       =    LiltForTokenClassification(config=lowerCamelCase__							)
							model.to(lowerCamelCase__							)
							model.eval()
							__lowerCamelCase		       =    model(
							    lowerCamelCase__			,						bbox=lowerCamelCase__			,						attention_mask=lowerCamelCase__			,						token_type_ids=lowerCamelCase__			,						labels=lowerCamelCase__							)
							self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.seq_length, self.num_labels)							)


			def       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						)    ->      Dict:



							'''simple docstring'''
							__lowerCamelCase		       =    LiltForQuestionAnswering(config=lowerCamelCase__							)
							model.to(lowerCamelCase__							)
							model.eval()
							__lowerCamelCase		       =    model(
							    lowerCamelCase__			,						bbox=lowerCamelCase__			,						attention_mask=lowerCamelCase__			,						token_type_ids=lowerCamelCase__			,						start_positions=lowerCamelCase__			,						end_positions=lowerCamelCase__			,						)
							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       lowercase_    (      self							)    ->      Tuple:



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







@require_torch
class     __lowerCAmelCase (       __magic_name__			,				__magic_name__			,				__magic_name__			,				unittest.TestCase ):

			"""simple docstring"""







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


			def       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      List[Any]:



							'''simple docstring'''
							return True


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



							'''simple docstring'''
							__lowerCamelCase		       =    LiltModelTester(self							)
							__lowerCamelCase		       =    ConfigTester(self			,						config_class=lowerCamelCase__			,						hidden_size=37							)


			def       lowercase_    (      self							)    ->      int:



							'''simple docstring'''
							self.config_tester.run_common_tests()


			def       lowercase_    (      self							)    ->      str:



							'''simple docstring'''
							__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowerCamelCase__							)


			def       lowercase_    (      self							)    ->      Dict:



							'''simple docstring'''
							__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs()
							for type in ["absolute", "relative_key", "relative_key_query"]:
											__lowerCamelCase		       =    type
											self.model_tester.create_and_check_model(*lowerCamelCase__							)


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



							'''simple docstring'''
							__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_token_classification(*lowerCamelCase__							)


			def       lowercase_    (      self							)    ->      Tuple:



							'''simple docstring'''
							__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_question_answering(*lowerCamelCase__							)






			@slow
			def       lowercase_    (      self							)    ->      Any:



							'''simple docstring'''
							for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__lowerCamelCase		       =    LiltModel.from_pretrained(lowerCamelCase__							)
											self.assertIsNotNone(lowerCamelCase__							)







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

			"""simple docstring"""







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



							'''simple docstring'''
							__lowerCamelCase		       =    LiltModel.from_pretrained('SCUT-DLVCLab/lilt-roberta-en-base'							).to(lowerCamelCase__							)

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

							# forward pass
							with torch.no_grad():
											__lowerCamelCase		       =    model(input_ids=lowerCamelCase__			,						bbox=lowerCamelCase__							)

							__lowerCamelCase		       =    torch.Size([1, 2, 768]							)
							__lowerCamelCase		       =    torch.tensor(
							    [[-0.06_53, 0.09_50, -0.00_61], [-0.05_45, 0.09_26, -0.03_24]]			,						device=lowerCamelCase__			,						)

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



import json
import os
import unittest

from transformers import DebertaTokenizer, DebertaTokenizerFast
from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES
from transformers.testing_utils import slow

from ...test_tokenization_common import TokenizerTesterMixin


class      lowerCamelCase    (SCREAMING_SNAKE_CASE__     ,					unittest.TestCase    ):
  """simple docstring"""







  lowerCamelCase__   =  DebertaTokenizer
  lowerCamelCase__   =  True
  lowerCamelCase__   =  DebertaTokenizerFast







  def       __A   (							self       :				List[Any]      )     ->		Dict:
        super().setUp()

        # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
        SCREAMING_SNAKE_CASE_      =     [
            "l",
            "o",
            "w",
            "e",
            "r",
            "s",
            "t",
            "i",
            "d",
            "n",
            "\u0120",
            "\u0120l",
            "\u0120n",
            "\u0120lo",
            "\u0120low",
            "er",
            "\u0120lowest",
            "\u0120newer",
            "\u0120wider",
            "[UNK]",
        ]
        SCREAMING_SNAKE_CASE_      =     dict(zip(__magic_name__     ,   range(len(__magic_name__      )      )      )      )
        SCREAMING_SNAKE_CASE_      =     ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
        SCREAMING_SNAKE_CASE_      =     {"unk_token": "[UNK]"}

        SCREAMING_SNAKE_CASE_      =     os.path.join(self.tmpdirname     ,   VOCAB_FILES_NAMES["vocab_file"]      )
        SCREAMING_SNAKE_CASE_      =     os.path.join(self.tmpdirname     ,   VOCAB_FILES_NAMES["merges_file"]      )
        with open(self.vocab_file     ,   "w"     ,   encoding="utf-8"      ) as fp:
              fp.write(json.dumps(__magic_name__      ) + "\n"      )
        with open(self.merges_file     ,   "w"     ,   encoding="utf-8"      ) as fp:
              fp.write("\n".join(__magic_name__      )      )







  def       __A   (							self       :				str     ,   **__magic_name__       :				int      )     ->		Union[str, Any]:
        kwargs.update(self.special_tokens_map      )
        return self.tokenizer_class.from_pretrained(self.tmpdirname     ,   **__magic_name__      )







  def       __A   (							self       :				str     ,   __magic_name__       :				List[Any]      )     ->		Dict:
        SCREAMING_SNAKE_CASE_      =     "lower newer"
        SCREAMING_SNAKE_CASE_      =     "lower newer"
        return input_text, output_text







  def       __A   (							self       :				Union[str, Any]      )     ->		str:
        SCREAMING_SNAKE_CASE_      =     self.get_tokenizer()
        SCREAMING_SNAKE_CASE_      =     "lower newer"
        SCREAMING_SNAKE_CASE_      =     ["l", "o", "w", "er", "\u0120", "n", "e", "w", "er"]
        SCREAMING_SNAKE_CASE_      =     tokenizer.tokenize(__magic_name__      )
        self.assertListEqual(__magic_name__     ,   __magic_name__      )

        SCREAMING_SNAKE_CASE_      =     tokens + [tokenizer.unk_token]
        SCREAMING_SNAKE_CASE_      =     [0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
        self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__      )     ,   __magic_name__      )







  def       __A   (							self       :				Optional[int]      )     ->		Optional[Any]:
        SCREAMING_SNAKE_CASE_      =     self.get_tokenizer()
        SCREAMING_SNAKE_CASE_      =     tokenizer("Hello"     ,   "World"      )
        SCREAMING_SNAKE_CASE_      =     [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
        self.assertListEqual(tokd["token_type_ids"]     ,   __magic_name__      )







  @slow
  def       __A   (							self       :				Any      )     ->		Any:
        SCREAMING_SNAKE_CASE_      =     self.tokenizer_class.from_pretrained("microsoft/deberta-base"      )

        SCREAMING_SNAKE_CASE_      =     tokenizer.encode("sequence builders"     ,   add_special_tokens=__magic_name__      )
        SCREAMING_SNAKE_CASE_      =     tokenizer.encode("multi-sequence build"     ,   add_special_tokens=__magic_name__      )

        SCREAMING_SNAKE_CASE_      =     tokenizer.encode(
            "sequence builders"     ,   add_special_tokens=__magic_name__     ,   add_prefix_space=__magic_name__      )
        SCREAMING_SNAKE_CASE_      =     tokenizer.encode(
            "sequence builders"     ,   "multi-sequence build"     ,   add_special_tokens=__magic_name__     ,   add_prefix_space=__magic_name__      )

        SCREAMING_SNAKE_CASE_      =     tokenizer.build_inputs_with_special_tokens(__magic_name__      )
        SCREAMING_SNAKE_CASE_      =     tokenizer.build_inputs_with_special_tokens(__magic_name__     ,   __magic_name__      )

        assert encoded_sentence == encoded_text_from_decode
        assert encoded_pair == encoded_pair_from_decode







  @slow
  def       __A   (							self       :				Tuple      )     ->		str:
        SCREAMING_SNAKE_CASE_      =     [self.tokenizer_class]
        if self.test_rust_tokenizer:
              tokenizer_classes.append(self.rust_tokenizer_class      )

        for tokenizer_class in tokenizer_classes:
              SCREAMING_SNAKE_CASE_      =     tokenizer_class.from_pretrained("microsoft/deberta-base"      )

              SCREAMING_SNAKE_CASE_      =     [
                  "ALBERT: A Lite BERT for Self-supervised Learning of Language Representations",
                  "ALBERT incorporates two parameter reduction techniques",
                  "The first one is a factorized embedding parameterization. By decomposing the large vocabulary"
                  " embedding matrix into two small matrices, we separate the size of the hidden layers from the size of"
                  " vocabulary embedding.",
              ]

              SCREAMING_SNAKE_CASE_      =     tokenizer(__magic_name__     ,   padding=__magic_name__      )
              SCREAMING_SNAKE_CASE_      =     [tokenizer.decode(__magic_name__     ,   skip_special_tokens=__magic_name__      ) for seq in encoding["input_ids"]]

              # fmt: off
              SCREAMING_SNAKE_CASE_      =     {
                  "input_ids": [
                      [1, 2_118, 11_126, 565, 35, 83, 25_191, 163, 18_854, 13, 12_156, 12, 16_101, 25_376, 13_807, 9, 22_205, 27_893, 1_635, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      [1, 2_118, 11_126, 565, 24_536, 80, 43_797, 4_878, 7_373, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      [1, 133, 78, 65, 16, 10, 3_724, 1_538, 33_183, 11_303, 43_797, 1_938, 4, 870, 24_165, 29_105, 5, 739, 32_644, 33_183, 11_303, 36_173, 88, 80, 650, 7_821, 45_940, 6, 52, 2_559, 5, 1_836, 9, 5, 7_397, 13_171, 31, 5, 1_836, 9, 32_644, 33_183, 11_303, 4, 2]
                  ],
                  "token_type_ids": [
                      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                  ],
                  "attention_mask": [
                      [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
                  ]
              }
              # fmt: on

              SCREAMING_SNAKE_CASE_      =     [
                  "ALBERT: A Lite BERT for Self-supervised Learning of Language Representations",
                  "ALBERT incorporates two parameter reduction techniques",
                  "The first one is a factorized embedding parameterization. By decomposing the large vocabulary"
                  " embedding matrix into two small matrices, we separate the size of the hidden layers from the size of"
                  " vocabulary embedding.",
              ]

              self.assertDictEqual(encoding.data     ,   __magic_name__      )

              for expected, decoded in zip(__magic_name__     ,   __magic_name__      ):
                    self.assertEqual(__magic_name__     ,   __magic_name__      )


