






"""simple docstring"""

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				( A__ ,							unittest.TestCase			):





		'''simple docstring'''






		a_	:				Optional[Any]            =							DebertaTokenizer
		a_	:				int            =							True
		a_	:				Optional[int]            =							DebertaTokenizerFast





		def    lowerCamelCase       (   self							:	str	):
				super().setUp()

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

				lowerCAmelCase_   :							List[str]									=			os.path.join(self.tmpdirname						,			VOCAB_FILES_NAMES["vocab_file"]	)
				lowerCAmelCase_   :							str									=			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(__a	) + "\n"	)
				with open(self.merges_file						,			"w"						,			encoding="utf-8"	) as fp:
						fp.write("\n".join(__a	)	)





		def    lowerCamelCase       (   self							:	Optional[int]						,			**a_							:	List[Any]	):
				kwargs.update(self.special_tokens_map	)
				return self.tokenizer_class.from_pretrained(self.tmpdirname						,			**__a	)





		def    lowerCamelCase       (   self							:	List[str]						,			a_							:	Optional[int]	):
				lowerCAmelCase_   :							int									=			"lower newer"
				lowerCAmelCase_   :							List[str]									=			"lower newer"
				return input_text, output_text





		def    lowerCamelCase       (   self							:	Optional[Any]	):
				lowerCAmelCase_   :							int									=			self.get_tokenizer()
				lowerCAmelCase_   :							Dict									=			"lower newer"
				lowerCAmelCase_   :							List[Any]									=			["l", "o", "w", "er", "\u0120", "n", "e", "w", "er"]
				lowerCAmelCase_   :							Dict									=			tokenizer.tokenize(__a	)
				self.assertListEqual(__a						,			__a	)

				lowerCAmelCase_   :							Dict									=			tokens + [tokenizer.unk_token]
				lowerCAmelCase_   :							Any									=			[0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
				self.assertListEqual(tokenizer.convert_tokens_to_ids(__a	)						,			__a	)





		def    lowerCamelCase       (   self							:	str	):
				lowerCAmelCase_   :							Union[str, Any]									=			self.get_tokenizer()
				lowerCAmelCase_   :							str									=			tokenizer("Hello"						,			"World"	)
				lowerCAmelCase_   :							Optional[int]									=			[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
				self.assertListEqual(tokd["token_type_ids"]						,			__a	)





		@slow
		def    lowerCamelCase       (   self							:	Optional[Any]	):
				lowerCAmelCase_   :							List[Any]									=			self.tokenizer_class.from_pretrained("microsoft/deberta-base"	)

				lowerCAmelCase_   :							List[Any]									=			tokenizer.encode("sequence builders"						,			add_special_tokens=__a	)
				lowerCAmelCase_   :							str									=			tokenizer.encode("multi-sequence build"						,			add_special_tokens=__a	)

				lowerCAmelCase_   :							Tuple									=			tokenizer.encode(
				    "sequence builders"						,			add_special_tokens=__a						,			add_prefix_space=__a	)
				lowerCAmelCase_   :							Optional[Any]									=			tokenizer.encode(
				    "sequence builders"						,			"multi-sequence build"						,			add_special_tokens=__a						,			add_prefix_space=__a	)

				lowerCAmelCase_   :							Dict									=			tokenizer.build_inputs_with_special_tokens(__a	)
				lowerCAmelCase_   :							Any									=			tokenizer.build_inputs_with_special_tokens(__a						,			__a	)

				assert encoded_sentence == encoded_text_from_decode
				assert encoded_pair == encoded_pair_from_decode





		@slow
		def    lowerCamelCase       (   self							:	Any	):
				lowerCAmelCase_   :							Union[str, Any]									=			[self.tokenizer_class]
				if self.test_rust_tokenizer:
						tokenizer_classes.append(self.rust_tokenizer_class	)

				for tokenizer_class in tokenizer_classes:
						lowerCAmelCase_   :							List[Any]									=			tokenizer_class.from_pretrained("microsoft/deberta-base"	)

						lowerCAmelCase_   :							int									=			[
						    "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.",
						]

						lowerCAmelCase_   :							Dict									=			tokenizer(__a						,			padding=__a	)
						lowerCAmelCase_   :							Tuple									=			[tokenizer.decode(__a						,			skip_special_tokens=__a	) for seq in encoding["input_ids"]]

						# fmt: off
						lowerCAmelCase_   :							int									=			{
						    "input_ids": [
						        [1, 21_18, 1_11_26, 5_65, 35, 83, 2_51_91, 1_63, 1_88_54, 13, 1_21_56, 12, 1_61_01, 2_53_76, 1_38_07, 9, 2_22_05, 2_78_93, 16_35, 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, 21_18, 1_11_26, 5_65, 2_45_36, 80, 4_37_97, 48_78, 73_73, 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, 1_33, 78, 65, 16, 10, 37_24, 15_38, 3_31_83, 1_13_03, 4_37_97, 19_38, 4, 8_70, 2_41_65, 2_91_05, 5, 7_39, 3_26_44, 3_31_83, 1_13_03, 3_61_73, 88, 80, 6_50, 78_21, 4_59_40, 6, 52, 25_59, 5, 18_36, 9, 5, 73_97, 1_31_71, 31, 5, 18_36, 9, 3_26_44, 3_31_83, 1_13_03, 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

						lowerCAmelCase_   :							int									=			[
						    "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						,			__a	)

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





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







							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=1000,			):

														'''simple docstring'''

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







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Dict    =    ids_tensor([self.batch_size, self.seq_length],			self.vocab_size)

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

														_lowerCAmelCase     :							Optional[Any]    =    None
														if self.use_input_mask:
																					_lowerCAmelCase     :							Union[str, Any]    =    ids_tensor([self.batch_size, self.seq_length],			vocab_size=2)

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

														_lowerCAmelCase     :							Optional[int]    =    None
														_lowerCAmelCase     :							Optional[Any]    =    None
														if self.use_labels:
																					_lowerCAmelCase     :							Optional[Any]    =    ids_tensor([self.batch_size],			self.type_sequence_label_size)
																					_lowerCAmelCase     :							Any    =    ids_tensor([self.batch_size, self.seq_length],			self.num_labels)

														_lowerCAmelCase     :							Optional[int]    =    self.get_config()

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







							def    snake_case__      (   self):

														'''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    snake_case__      (   self,			__a,			__a,			__a,			__a,			__a,			__a,			__a,			):

														'''simple docstring'''

														_lowerCAmelCase     :							Union[str, Any]    =    LiltModel(config=__a)
														model.to(__a)
														model.eval()
														_lowerCAmelCase     :							Dict    =    model(__a,			bbox=__a,			attention_mask=__a,			token_type_ids=__a)
														_lowerCAmelCase     :							str    =    model(__a,			bbox=__a,			token_type_ids=__a)
														_lowerCAmelCase     :							List[Any]    =    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    snake_case__      (   self,			__a,			__a,			__a,			__a,			__a,			__a,			__a,			):

														'''simple docstring'''

														_lowerCAmelCase     :							List[Any]    =    self.num_labels
														_lowerCAmelCase     :							Optional[Any]    =    LiltForTokenClassification(config=__a)
														model.to(__a)
														model.eval()
														_lowerCAmelCase     :							Dict    =    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    snake_case__      (   self,			__a,			__a,			__a,			__a,			__a,			__a,			__a,			):

														'''simple docstring'''

														_lowerCAmelCase     :							Optional[int]    =    LiltForQuestionAnswering(config=__a)
														model.to(__a)
														model.eval()
														_lowerCAmelCase     :							Tuple    =    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    snake_case__      (   self):

														'''simple docstring'''

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



@require_torch
class   UpperCAmelCase_    (       a   ,					a   ,					a   ,					unittest.TestCase):
							lowerCamelCase__   			=		(
							    (
							        LiltModel,
							        LiltForSequenceClassification,
							        LiltForTokenClassification,
							        LiltForQuestionAnswering,
							    )
							    if is_torch_available()
							    else ()
							)
							lowerCamelCase__   			=		(
							    {
							        'feature-extraction': LiltModel,
							        'question-answering': LiltForQuestionAnswering,
							        'text-classification': LiltForSequenceClassification,
							        'token-classification': LiltForTokenClassification,
							        'zero-shot': LiltForSequenceClassification,
							    }
							    if is_torch_available()
							    else {}
							)
							lowerCamelCase__   			=		False
							lowerCamelCase__   			=		False







							def    snake_case__      (   self,			__a,			__a,			__a,			__a,			__a):

														'''simple docstring'''

														return True







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Optional[Any]    =    LiltModelTester(self)
														_lowerCAmelCase     :							Union[str, Any]    =    ConfigTester(self,			config_class=__a,			hidden_size=37)







							def    snake_case__      (   self):

														'''simple docstring'''

														self.config_tester.run_common_tests()







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Dict    =    self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*__a)







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							int    =    self.model_tester.prepare_config_and_inputs()
														for type in ["absolute", "relative_key", "relative_key_query"]:
																					_lowerCAmelCase     :							Any    =    type
																					self.model_tester.create_and_check_model(*__a)







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							int    =    self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_token_classification(*__a)







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Optional[int]    =    self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_question_answering(*__a)







							@slow
							def    snake_case__      (   self):

														'''simple docstring'''

														for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					_lowerCAmelCase     :							str    =    LiltModel.from_pretrained(__a)
																					self.assertIsNotNone(__a)



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







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Dict    =    LiltModel.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base").to(__a)

														_lowerCAmelCase     :							Any    =    torch.tensor([[1, 2]],			device=__a)
														_lowerCAmelCase     :							str    =    torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]],			device=__a)

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

														_lowerCAmelCase     :							Optional[int]    =    torch.Size([1, 2, 768])
														_lowerCAmelCase     :							List[str]    =    torch.tensor(
														    [[-0.0_653, 0.0_950, -0.0_061], [-0.0_545, 0.0_926, -0.0_324]],			device=__a,			)

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