

import os
import shutil
import sys
import tempfile
import unittest
from pathlib import Path

import pytest

import transformers
from transformers import (
    BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    AutoTokenizer,
    BertConfig,
    BertTokenizer,
    BertTokenizerFast,
    CTRLTokenizer,
    GPTaTokenizer,
    GPTaTokenizerFast,
    PreTrainedTokenizerFast,
    RobertaTokenizer,
    RobertaTokenizerFast,
    is_tokenizers_available,
)
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.auto.tokenization_auto import (
    TOKENIZER_MAPPING,
    get_tokenizer_config,
    tokenizer_class_from_name,
)
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import (
    DUMMY_DIFF_TOKENIZER_IDENTIFIER,
    DUMMY_UNKNOWN_IDENTIFIER,
    SMALL_MODEL_IDENTIFIER,
    RequestCounter,
    require_tokenizers,
    slow,
)


sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils"""))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_tokenization import CustomTokenizer  # noqa E402


if is_tokenizers_available():
      from test_module.custom_tokenization_fast import CustomTokenizerFast

class    _lowercase				(					unittest.TestCase			):

   def     UpperCamelCase					(				self	:    Optional[int]       ) ->			Union[str, Any]:
         """simple docstring"""





         A_							       =		0

   @slow
   def     UpperCamelCase					(				self	:    Any       ) ->			str:
         """simple docstring"""





         for model_name in (x for x in BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys() if "japanese" not in x):
               A_							       =		AutoTokenizer.from_pretrained(lowerCamelCase__       )
               self.assertIsNotNone(lowerCamelCase__       )
               self.assertIsInstance(lowerCamelCase__			,						(BertTokenizer, BertTokenizerFast)       )
               self.assertGreater(len(lowerCamelCase__       )			,						0       )

         for model_name in GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP.keys():
               A_							       =		AutoTokenizer.from_pretrained(lowerCamelCase__       )
               self.assertIsNotNone(lowerCamelCase__       )
               self.assertIsInstance(lowerCamelCase__			,						(GPTaTokenizer, GPTaTokenizerFast)       )
               self.assertGreater(len(lowerCamelCase__       )			,						0       )

   def     UpperCamelCase					(				self	:    Union[str, Any]       ) ->			List[Any]:
         """simple docstring"""





         A_							       =		AutoTokenizer.from_pretrained(lowerCamelCase__       )
         self.assertIsInstance(lowerCamelCase__			,						(BertTokenizer, BertTokenizerFast)       )
         self.assertEqual(tokenizer.vocab_size			,						1_2       )

   def     UpperCamelCase					(				self	:    List[str]       ) ->			List[str]:
         """simple docstring"""





         A_							       =		AutoTokenizer.from_pretrained(lowerCamelCase__       )
         self.assertIsInstance(lowerCamelCase__			,						(RobertaTokenizer, RobertaTokenizerFast)       )
         self.assertEqual(tokenizer.vocab_size			,						2_0       )

   def     UpperCamelCase					(				self	:    Union[str, Any]       ) ->			Optional[Any]:
         """simple docstring"""





         A_							       =		AutoConfig.from_pretrained(lowerCamelCase__       )
         self.assertIsInstance(lowerCamelCase__			,						lowerCamelCase__       )
         # Check that tokenizer_type ≠ model_type
         A_							       =		AutoTokenizer.from_pretrained(lowerCamelCase__			,						config=lowerCamelCase__       )
         self.assertIsInstance(lowerCamelCase__			,						(BertTokenizer, BertTokenizerFast)       )
         self.assertEqual(tokenizer.vocab_size			,						1_2       )

   def     UpperCamelCase					(				self	:    str       ) ->			str:
         """simple docstring"""





         with tempfile.TemporaryDirectory() as tmp_dir:
               shutil.copy('''./tests/fixtures/vocab.txt'''			,						os.path.join(lowerCamelCase__			,						'''vocab.txt'''       )       )

               A_							       =		AutoTokenizer.from_pretrained(lowerCamelCase__			,						tokenizer_type='''bert'''			,						use_fast=lowerCamelCase__       )
               self.assertIsInstance(lowerCamelCase__			,						lowerCamelCase__       )

         with tempfile.TemporaryDirectory() as tmp_dir:
               shutil.copy('''./tests/fixtures/vocab.json'''			,						os.path.join(lowerCamelCase__			,						'''vocab.json'''       )       )
               shutil.copy('''./tests/fixtures/merges.txt'''			,						os.path.join(lowerCamelCase__			,						'''merges.txt'''       )       )

               A_							       =		AutoTokenizer.from_pretrained(lowerCamelCase__			,						tokenizer_type='''gpt2'''			,						use_fast=lowerCamelCase__       )
               self.assertIsInstance(lowerCamelCase__			,						lowerCamelCase__       )

   @require_tokenizers
   def     UpperCamelCase					(				self	:    List[Any]       ) ->			List[Any]:
         """simple docstring"""





         with tempfile.TemporaryDirectory() as tmp_dir:
               shutil.copy('''./tests/fixtures/vocab.txt'''			,						os.path.join(lowerCamelCase__			,						'''vocab.txt'''       )       )

               A_							       =		AutoTokenizer.from_pretrained(lowerCamelCase__			,						tokenizer_type='''bert'''       )
               self.assertIsInstance(lowerCamelCase__			,						lowerCamelCase__       )

         with tempfile.TemporaryDirectory() as tmp_dir:
               shutil.copy('''./tests/fixtures/vocab.json'''			,						os.path.join(lowerCamelCase__			,						'''vocab.json'''       )       )
               shutil.copy('''./tests/fixtures/merges.txt'''			,						os.path.join(lowerCamelCase__			,						'''merges.txt'''       )       )

               A_							       =		AutoTokenizer.from_pretrained(lowerCamelCase__			,						tokenizer_type='''gpt2'''       )
               self.assertIsInstance(lowerCamelCase__			,						lowerCamelCase__       )

   def     UpperCamelCase					(				self	:    List[Any]       ) ->			int:
         """simple docstring"""





         with pytest.raises(lowerCamelCase__       ):
               AutoTokenizer.from_pretrained('''./'''			,						tokenizer_type='''xxx'''       )

   @require_tokenizers
   def     UpperCamelCase					(				self	:    str       ) ->			Union[str, Any]:
         """simple docstring"""





         for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]:
               A_							       =		tokenizer_class.from_pretrained('''wietsedv/bert-base-dutch-cased'''       )
               self.assertIsInstance(lowerCamelCase__			,						(BertTokenizer, BertTokenizerFast)       )

               if isinstance(lowerCamelCase__			,						lowerCamelCase__       ):
                     self.assertEqual(tokenizer.basic_tokenizer.do_lower_case			,						lowerCamelCase__       )
               else:
                     self.assertEqual(tokenizer.do_lower_case			,						lowerCamelCase__       )

               self.assertEqual(tokenizer.model_max_length			,						5_1_2       )

   @require_tokenizers
   def     UpperCamelCase					(				self	:    Any       ) ->			int:
         """simple docstring"""





         for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]:
               with self.assertRaisesRegex(
                   lowerCamelCase__			,						'''julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier'''			,						):
                     A_							       =		tokenizer_class.from_pretrained('''julien-c/herlolip-not-exists'''       )

   def     UpperCamelCase					(				self	:    Union[str, Any]       ) ->			Dict:
         """simple docstring"""





         A_							       =		TOKENIZER_MAPPING.values()
         A_							       =		[]

         for slow_tok, fast_tok in tokenizers:
               if slow_tok is not None:
                     tokenizer_names.append(slow_tok.__name__       )

               if fast_tok is not None:
                     tokenizer_names.append(fast_tok.__name__       )

         for tokenizer_name in tokenizer_names:
               # must find the right class
               tokenizer_class_from_name(lowerCamelCase__       )

   @require_tokenizers
   def     UpperCamelCase					(				self	:    int       ) ->			int:
         """simple docstring"""





         self.assertIsInstance(AutoTokenizer.from_pretrained('''bert-base-cased'''			,						use_fast=lowerCamelCase__       )			,						lowerCamelCase__       )
         self.assertIsInstance(AutoTokenizer.from_pretrained('''bert-base-cased'''       )			,						lowerCamelCase__       )

   @require_tokenizers
   def     UpperCamelCase					(				self	:    Optional[Any]       ) ->			str:
         """simple docstring"""





         A_							       =		AutoTokenizer.from_pretrained('''distilbert-base-uncased'''			,						do_lower_case=lowerCamelCase__       )
         A_							       =		'''Hello, world. How are you?'''
         A_							       =		tokenizer.tokenize(lowerCamelCase__       )
         self.assertEqual('''[UNK]'''			,						tokens[0]       )

         A_							       =		AutoTokenizer.from_pretrained('''microsoft/mpnet-base'''			,						do_lower_case=lowerCamelCase__       )
         A_							       =		tokenizer.tokenize(lowerCamelCase__       )
         self.assertEqual('''[UNK]'''			,						tokens[0]       )

   @require_tokenizers
   def     UpperCamelCase					(				self	:    Tuple       ) ->			int:
         """simple docstring"""





         A_							       =		AutoTokenizer.from_pretrained('''robot-test/dummy-tokenizer-fast-with-model-config'''       )
         self.assertEqual(type(lowerCamelCase__       )			,						lowerCamelCase__       )
         self.assertEqual(tokenizer.model_max_length			,						5_1_2       )
         self.assertEqual(tokenizer.vocab_size			,						3_0_0_0_0       )
         self.assertEqual(tokenizer.unk_token			,						'''[UNK]'''       )
         self.assertEqual(tokenizer.padding_side			,						'''right'''       )
         self.assertEqual(tokenizer.truncation_side			,						'''right'''       )

   def     UpperCamelCase					(				self	:    Dict       ) ->			Any:
         """simple docstring"""





         A_							       =		AutoTokenizer.from_pretrained(lowerCamelCase__       )
         self.assertIsInstance(lowerCamelCase__			,						(BertTokenizer, BertTokenizerFast)       )
         with tempfile.TemporaryDirectory() as tmp_dir:
               tokenizer.save_pretrained(lowerCamelCase__       )
               A_							       =		AutoTokenizer.from_pretrained(lowerCamelCase__       )

         self.assertIsInstance(lowerCamelCase__			,						tokenizer.__class__       )
         self.assertEqual(tokenizera.vocab_size			,						1_2       )

   def     UpperCamelCase					(				self	:    Optional[int]       ) ->			Optional[int]:
         """simple docstring"""





         A_							       =		AutoTokenizer.from_pretrained('''ctrl'''       )
         # There is no fast CTRL so this always gives us a slow tokenizer.
         self.assertIsInstance(lowerCamelCase__			,						lowerCamelCase__       )

   def     UpperCamelCase					(				self	:    Dict       ) ->			Any:
         """simple docstring"""





         A_							       =		get_tokenizer_config('''bert-base-cased'''       )
         A_							       =		config.pop('''_commit_hash'''			,						lowerCamelCase__       )
         # If we ever update bert-base-cased tokenizer config, this dict here will need to be updated.
         self.assertEqual(lowerCamelCase__			,						{'''do_lower_case''': False}       )

         # This model does not have a tokenizer_config so we get back an empty dict.
         A_							       =		get_tokenizer_config(lowerCamelCase__       )
         self.assertDictEqual(lowerCamelCase__			,						{}       )

         # A tokenizer saved with `save_pretrained` always creates a tokenizer config.
         A_							       =		AutoTokenizer.from_pretrained(lowerCamelCase__       )
         with tempfile.TemporaryDirectory() as tmp_dir:
               tokenizer.save_pretrained(lowerCamelCase__       )
               A_							       =		get_tokenizer_config(lowerCamelCase__       )

         # Check the class of the tokenizer was properly saved (note that it always saves the slow class).
         self.assertEqual(config['''tokenizer_class''']			,						'''BertTokenizer'''       )

   def     UpperCamelCase					(				self	:    str       ) ->			Optional[Any]:
         """simple docstring"""





         try:
               AutoConfig.register('''custom'''			,						lowerCamelCase__       )

               AutoTokenizer.register(lowerCamelCase__			,						slow_tokenizer_class=lowerCamelCase__       )
               # Trying to register something existing in the Transformers library will raise an error
               with self.assertRaises(lowerCamelCase__       ):
                     AutoTokenizer.register(lowerCamelCase__			,						slow_tokenizer_class=lowerCamelCase__       )

               A_							       =		CustomTokenizer.from_pretrained(lowerCamelCase__       )
               with tempfile.TemporaryDirectory() as tmp_dir:
                     tokenizer.save_pretrained(lowerCamelCase__       )

                     A_							       =		AutoTokenizer.from_pretrained(lowerCamelCase__       )
                     self.assertIsInstance(lowerCamelCase__			,						lowerCamelCase__       )

         finally:
               if "custom" in CONFIG_MAPPING._extra_content:
                     del CONFIG_MAPPING._extra_content["custom"]
               if CustomConfig in TOKENIZER_MAPPING._extra_content:
                     del TOKENIZER_MAPPING._extra_content[CustomConfig]

   @require_tokenizers
   def     UpperCamelCase					(				self	:    Optional[Any]       ) ->			List[Any]:
         """simple docstring"""





         try:
               AutoConfig.register('''custom'''			,						lowerCamelCase__       )

               # Can register in two steps
               AutoTokenizer.register(lowerCamelCase__			,						slow_tokenizer_class=lowerCamelCase__       )
               self.assertEqual(TOKENIZER_MAPPING[CustomConfig]			,						(CustomTokenizer, None)       )
               AutoTokenizer.register(lowerCamelCase__			,						fast_tokenizer_class=lowerCamelCase__       )
               self.assertEqual(TOKENIZER_MAPPING[CustomConfig]			,						(CustomTokenizer, CustomTokenizerFast)       )

               del TOKENIZER_MAPPING._extra_content[CustomConfig]
               # Can register in one step
               AutoTokenizer.register(
                   lowerCamelCase__			,						slow_tokenizer_class=lowerCamelCase__			,						fast_tokenizer_class=lowerCamelCase__       )
               self.assertEqual(TOKENIZER_MAPPING[CustomConfig]			,						(CustomTokenizer, CustomTokenizerFast)       )

               # Trying to register something existing in the Transformers library will raise an error
               with self.assertRaises(lowerCamelCase__       ):
                     AutoTokenizer.register(lowerCamelCase__			,						fast_tokenizer_class=lowerCamelCase__       )

               # We pass through a bert tokenizer fast cause there is no converter slow to fast for our new toknizer
               # and that model does not have a tokenizer.json
               with tempfile.TemporaryDirectory() as tmp_dir:
                     A_							       =		BertTokenizerFast.from_pretrained(lowerCamelCase__       )
                     bert_tokenizer.save_pretrained(lowerCamelCase__       )
                     A_							       =		CustomTokenizerFast.from_pretrained(lowerCamelCase__       )

               with tempfile.TemporaryDirectory() as tmp_dir:
                     tokenizer.save_pretrained(lowerCamelCase__       )

                     A_							       =		AutoTokenizer.from_pretrained(lowerCamelCase__       )
                     self.assertIsInstance(lowerCamelCase__			,						lowerCamelCase__       )

                     A_							       =		AutoTokenizer.from_pretrained(lowerCamelCase__			,						use_fast=lowerCamelCase__       )
                     self.assertIsInstance(lowerCamelCase__			,						lowerCamelCase__       )

         finally:
               if "custom" in CONFIG_MAPPING._extra_content:
                     del CONFIG_MAPPING._extra_content["custom"]
               if CustomConfig in TOKENIZER_MAPPING._extra_content:
                     del TOKENIZER_MAPPING._extra_content[CustomConfig]

   def     UpperCamelCase					(				self	:    List[Any]       ) ->			Union[str, Any]:
         """simple docstring"""





         with self.assertRaises(lowerCamelCase__       ):
               A_							       =		AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer'''       )
         # If remote code is disabled, we can't load this config.
         with self.assertRaises(lowerCamelCase__       ):
               A_							       =		AutoTokenizer.from_pretrained(
                   '''hf-internal-testing/test_dynamic_tokenizer'''			,						trust_remote_code=lowerCamelCase__       )

         A_							       =		AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer'''			,						trust_remote_code=lowerCamelCase__       )
         self.assertTrue(tokenizer.special_attribute_present       )
         # Test tokenizer can be reloaded.
         with tempfile.TemporaryDirectory() as tmp_dir:
               tokenizer.save_pretrained(lowerCamelCase__       )
               A_							       =		AutoTokenizer.from_pretrained(lowerCamelCase__			,						trust_remote_code=lowerCamelCase__       )
         self.assertTrue(reloaded_tokenizer.special_attribute_present       )

         if is_tokenizers_available():
               self.assertEqual(tokenizer.__class__.__name__			,						'''NewTokenizerFast'''       )
               self.assertEqual(reloaded_tokenizer.__class__.__name__			,						'''NewTokenizerFast'''       )

               # Test we can also load the slow version
               A_							       =		AutoTokenizer.from_pretrained(
                   '''hf-internal-testing/test_dynamic_tokenizer'''			,						trust_remote_code=lowerCamelCase__			,						use_fast=lowerCamelCase__       )
               self.assertTrue(tokenizer.special_attribute_present       )
               self.assertEqual(tokenizer.__class__.__name__			,						'''NewTokenizer'''       )
               # Test tokenizer can be reloaded.
               with tempfile.TemporaryDirectory() as tmp_dir:
                     tokenizer.save_pretrained(lowerCamelCase__       )
                     A_							       =		AutoTokenizer.from_pretrained(lowerCamelCase__			,						trust_remote_code=lowerCamelCase__			,						use_fast=lowerCamelCase__       )
               self.assertEqual(reloaded_tokenizer.__class__.__name__			,						'''NewTokenizer'''       )
               self.assertTrue(reloaded_tokenizer.special_attribute_present       )
         else:
               self.assertEqual(tokenizer.__class__.__name__			,						'''NewTokenizer'''       )
               self.assertEqual(reloaded_tokenizer.__class__.__name__			,						'''NewTokenizer'''       )

   @require_tokenizers
   def     UpperCamelCase					(				self	:    Any       ) ->			List[Any]:
         """simple docstring"""





         class    _lowercase				(					__lowerCamelCase			):
            _lowercase     :       Optional[int]  					=    False



         class    _lowercase				(					__lowerCamelCase			):
            _lowercase     :       List[Any]  					=    NewTokenizer
            _lowercase     :       Optional[Any]  					=    False

         try:
               AutoConfig.register('''custom'''			,						lowerCamelCase__       )
               AutoTokenizer.register(lowerCamelCase__			,						slow_tokenizer_class=lowerCamelCase__       )
               AutoTokenizer.register(lowerCamelCase__			,						fast_tokenizer_class=lowerCamelCase__       )
               # If remote code is not set, the default is to use local
               A_							       =		AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer'''       )
               self.assertEqual(tokenizer.__class__.__name__			,						'''NewTokenizerFast'''       )
               self.assertFalse(tokenizer.special_attribute_present       )
               A_							       =		AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer'''			,						use_fast=lowerCamelCase__       )
               self.assertEqual(tokenizer.__class__.__name__			,						'''NewTokenizer'''       )
               self.assertFalse(tokenizer.special_attribute_present       )

               # If remote code is disabled, we load the local one.
               A_							       =		AutoTokenizer.from_pretrained(
                   '''hf-internal-testing/test_dynamic_tokenizer'''			,						trust_remote_code=lowerCamelCase__       )
               self.assertEqual(tokenizer.__class__.__name__			,						'''NewTokenizerFast'''       )
               self.assertFalse(tokenizer.special_attribute_present       )
               A_							       =		AutoTokenizer.from_pretrained(
                   '''hf-internal-testing/test_dynamic_tokenizer'''			,						trust_remote_code=lowerCamelCase__			,						use_fast=lowerCamelCase__       )
               self.assertEqual(tokenizer.__class__.__name__			,						'''NewTokenizer'''       )
               self.assertFalse(tokenizer.special_attribute_present       )

               # If remote is enabled, we load from the Hub
               A_							       =		AutoTokenizer.from_pretrained(
                   '''hf-internal-testing/test_dynamic_tokenizer'''			,						trust_remote_code=lowerCamelCase__       )
               self.assertEqual(tokenizer.__class__.__name__			,						'''NewTokenizerFast'''       )
               self.assertTrue(tokenizer.special_attribute_present       )
               A_							       =		AutoTokenizer.from_pretrained(
                   '''hf-internal-testing/test_dynamic_tokenizer'''			,						trust_remote_code=lowerCamelCase__			,						use_fast=lowerCamelCase__       )
               self.assertEqual(tokenizer.__class__.__name__			,						'''NewTokenizer'''       )
               self.assertTrue(tokenizer.special_attribute_present       )

         finally:
               if "custom" in CONFIG_MAPPING._extra_content:
                     del CONFIG_MAPPING._extra_content["custom"]
               if CustomConfig in TOKENIZER_MAPPING._extra_content:
                     del TOKENIZER_MAPPING._extra_content[CustomConfig]

   def     UpperCamelCase					(				self	:    str       ) ->			Union[str, Any]:
         """simple docstring"""





         A_							       =		AutoTokenizer.from_pretrained(
             '''hf-internal-testing/test_dynamic_tokenizer_legacy'''			,						trust_remote_code=lowerCamelCase__       )
         self.assertTrue(tokenizer.special_attribute_present       )
         if is_tokenizers_available():
               self.assertEqual(tokenizer.__class__.__name__			,						'''NewTokenizerFast'''       )

               # Test we can also load the slow version
               A_							       =		AutoTokenizer.from_pretrained(
                   '''hf-internal-testing/test_dynamic_tokenizer_legacy'''			,						trust_remote_code=lowerCamelCase__			,						use_fast=lowerCamelCase__       )
               self.assertTrue(tokenizer.special_attribute_present       )
               self.assertEqual(tokenizer.__class__.__name__			,						'''NewTokenizer'''       )
         else:
               self.assertEqual(tokenizer.__class__.__name__			,						'''NewTokenizer'''       )

   def     UpperCamelCase					(				self	:    Any       ) ->			Dict:
         """simple docstring"""





         with self.assertRaisesRegex(
             lowerCamelCase__			,						'''bert-base is not a local folder and is not a valid model identifier'''       ):
               A_							       =		AutoTokenizer.from_pretrained('''bert-base'''       )

   def     UpperCamelCase					(				self	:    Any       ) ->			Optional[int]:
         """simple docstring"""





         with self.assertRaisesRegex(
             lowerCamelCase__			,						R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''       ):
               A_							       =		AutoTokenizer.from_pretrained(lowerCamelCase__			,						revision='''aaaaaa'''       )





   def     UpperCamelCase					(				self	:    int       ) ->			List[str]:
         """simple docstring"""





         A_							       =		AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert'''       )
         with RequestCounter() as counter:
               A_							       =		AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert'''       )
               self.assertEqual(counter.get_request_count			,						0       )
               self.assertEqual(counter.head_request_count			,						1       )
               self.assertEqual(counter.other_request_count			,						0       )








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

   def __init__(				self	:    Tuple			,						lowerCamelCase__	:    Optional[int]			,						lowerCamelCase__	:    Dict=1_3			,						lowerCamelCase__	:    Any=7			,						lowerCamelCase__	:    Optional[Any]=True			,						lowerCamelCase__	:    Optional[Any]=True			,						lowerCamelCase__	:    List[Any]=True			,						lowerCamelCase__	:    Union[str, Any]=True			,						lowerCamelCase__	:    Optional[int]=9_9			,						lowerCamelCase__	:    Optional[int]=2_4			,						lowerCamelCase__	:    Optional[int]=2			,						lowerCamelCase__	:    Dict=6			,						lowerCamelCase__	:    List[str]=3_7			,						lowerCamelCase__	:    Optional[Any]="gelu"			,						lowerCamelCase__	:    Dict=0.1			,						lowerCamelCase__	:    Optional[int]=0.1			,						lowerCamelCase__	:    Any=5_1_2			,						lowerCamelCase__	:    int=1_6			,						lowerCamelCase__	:    Union[str, Any]=2			,						lowerCamelCase__	:    Optional[int]=0.02			,						lowerCamelCase__	:    Optional[Any]=3			,						lowerCamelCase__	:    Optional[int]=None			,						lowerCamelCase__	:    Any=1_0_0_0			,						) ->			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     UpperCamelCase					(				self	:    int       ) ->			int:
         """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     UpperCamelCase					(				self	:    Optional[int]       ) ->			List[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     UpperCamelCase					(				self	:    Dict			,						lowerCamelCase__	:    Any			,						lowerCamelCase__	:    Union[str, Any]			,						lowerCamelCase__	:    List[Any]			,						lowerCamelCase__	:    Any			,						lowerCamelCase__	:    List[Any]			,						lowerCamelCase__	:    List[str]			,						lowerCamelCase__	:    Any			,						) ->			List[Any]:
         """simple docstring"""





         A_							       =		LiltModel(config=lowerCamelCase__       )
         model.to(lowerCamelCase__       )
         model.eval()
         A_							       =		model(lowerCamelCase__			,						bbox=lowerCamelCase__			,						attention_mask=lowerCamelCase__			,						token_type_ids=lowerCamelCase__       )
         A_							       =		model(lowerCamelCase__			,						bbox=lowerCamelCase__			,						token_type_ids=lowerCamelCase__       )
         A_							       =		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     UpperCamelCase					(				self	:    Optional[int]			,						lowerCamelCase__	:    str			,						lowerCamelCase__	:    Union[str, Any]			,						lowerCamelCase__	:    Union[str, Any]			,						lowerCamelCase__	:    Dict			,						lowerCamelCase__	:    List[Any]			,						lowerCamelCase__	:    Dict			,						lowerCamelCase__	:    Optional[Any]			,						) ->			Union[str, Any]:
         """simple docstring"""





         A_							       =		self.num_labels
         A_							       =		LiltForTokenClassification(config=lowerCamelCase__       )
         model.to(lowerCamelCase__       )
         model.eval()
         A_							       =		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     UpperCamelCase					(				self	:    Dict			,						lowerCamelCase__	:    List[Any]			,						lowerCamelCase__	:    str			,						lowerCamelCase__	:    str			,						lowerCamelCase__	:    Dict			,						lowerCamelCase__	:    Any			,						lowerCamelCase__	:    Any			,						lowerCamelCase__	:    List[str]			,						) ->			Any:
         """simple docstring"""





         A_							       =		LiltForQuestionAnswering(config=lowerCamelCase__       )
         model.to(lowerCamelCase__       )
         model.eval()
         A_							       =		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     UpperCamelCase					(				self	:    Optional[int]       ) ->			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    _lowercase				(					__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,unittest.TestCase			):
   _lowercase     :       Dict  					=    (
       (
           LiltModel,
           LiltForSequenceClassification,
           LiltForTokenClassification,
           LiltForQuestionAnswering,
       )
       if is_torch_available()
       else ()
   )
   _lowercase     :       List[Any]  					=    (
       {
           'feature-extraction': LiltModel,
           'question-answering': LiltForQuestionAnswering,
           'text-classification': LiltForSequenceClassification,
           'token-classification': LiltForTokenClassification,
           'zero-shot': LiltForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )
   _lowercase     :       Dict  					=    False
   _lowercase     :       Optional[int]  					=    False

   def     UpperCamelCase					(				self	:    Optional[Any]			,						lowerCamelCase__	:    Dict			,						lowerCamelCase__	:    int			,						lowerCamelCase__	:    List[str]			,						lowerCamelCase__	:    List[str]			,						lowerCamelCase__	:    List[str]       ) ->			Any:
         """simple docstring"""





         return True

   def     UpperCamelCase					(				self	:    int       ) ->			Any:
         """simple docstring"""





         A_							       =		LiltModelTester(self       )
         A_							       =		ConfigTester(self			,						config_class=lowerCamelCase__			,						hidden_size=3_7       )

   def     UpperCamelCase					(				self	:    int       ) ->			Optional[Any]:
         """simple docstring"""





         self.config_tester.run_common_tests()

   def     UpperCamelCase					(				self	:    Union[str, Any]       ) ->			Dict:
         """simple docstring"""





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

   def     UpperCamelCase					(				self	:    Optional[Any]       ) ->			int:
         """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(*lowerCamelCase__       )

   def     UpperCamelCase					(				self	:    List[Any]       ) ->			int:
         """simple docstring"""





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

   def     UpperCamelCase					(				self	:    List[str]       ) ->			Any:
         """simple docstring"""





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





   @slow
   def     UpperCamelCase					(				self	:    Any       ) ->			Dict:
         """simple docstring"""





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



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

   def     UpperCamelCase					(				self	:    List[str]       ) ->			Optional[Any]:
         """simple docstring"""





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

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

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

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

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





