

'''simple docstring'''


import json
from typing import TYPE_CHECKING, List, Optional, Tuple

from tokenizers import pre_tokenizers

from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging


if TYPE_CHECKING:
					from transformers.pipelines.conversational import Conversation


lowerCAmelCase__						:       Any										=						logging.get_logger(__name__)

lowerCAmelCase__						:       Optional[Any]										=						{"""tokenizer_file""": """tokenizer.json"""}

lowerCAmelCase__						:       str										=						{
    """tokenizer_file""": {
        """bigscience/tokenizer""": """https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json""",
        """bigscience/bloom-560m""": """https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json""",
        """bigscience/bloom-1b1""": """https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json""",
        """bigscience/bloom-1b7""": """https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json""",
        """bigscience/bloom-3b""": """https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json""",
        """bigscience/bloom-7b1""": """https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json""",
        """bigscience/bloom""": """https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json""",
    },
}




class     a			(				SCREAMING_SNAKE_CASE       ):






						"""simple docstring"""




						__UpperCAmelCase			     =    VOCAB_FILES_NAMES
						__UpperCAmelCase			     =    PRETRAINED_VOCAB_FILES_MAP
						__UpperCAmelCase			     =    ["""input_ids""", """attention_mask"""]
						__UpperCAmelCase			     =    None







						def __init__(							self					:      Optional[Any]			,			snake_case_					:      Optional[int]=None			,			snake_case_					:      Dict=None			,			snake_case_					:      Union[str, Any]=None			,			snake_case_					:      Tuple="<unk>"			,			snake_case_					:      int="<s>"			,			snake_case_					:      Union[str, Any]="</s>"			,			snake_case_					:      List[Any]="<pad>"			,			snake_case_					:      str=False			,			snake_case_					:      List[str]=False			,			**snake_case_					:      Any			,			):



								'''simple docstring'''



								super().__init__(
								    snake_case_			,			snake_case_			,			tokenizer_file=snake_case_			,			unk_token=snake_case_			,			bos_token=snake_case_			,			eos_token=snake_case_			,			pad_token=snake_case_			,			add_prefix_space=snake_case_			,			clean_up_tokenization_spaces=snake_case_			,			**snake_case_			,			)
								snake_case__						:       Tuple       						=  json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()  )
								if pre_tok_state.get('''add_prefix_space'''			,			snake_case_  ) != add_prefix_space:
										snake_case__						:       Any       						=  getattr(snake_case_			,			pre_tok_state.pop('''type'''  )  )
										snake_case__						:       str       						=  add_prefix_space
										snake_case__						:       Tuple       						=  pre_tok_class(**snake_case_  )

								snake_case__						:       List[Any]       						=  add_prefix_space







						def       __magic_name__							(							self					:      Optional[Any]			,			*snake_case_					:      int			,			**snake_case_					:      int  ):



								'''simple docstring'''



								snake_case__						:       int       						=  kwargs.get('''is_split_into_words'''			,			snake_case_  )
								if not (self.add_prefix_space or not is_split_into_words):
										raise Exception(
										    F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with"""
										    ''' pretokenized inputs.'''  )

								return super()._batch_encode_plus(*snake_case_			,			**snake_case_  )







						def       __magic_name__							(							self					:      int			,			*snake_case_					:      Any			,			**snake_case_					:      Any  ):



								'''simple docstring'''



								snake_case__						:       Any       						=  kwargs.get('''is_split_into_words'''			,			snake_case_  )

								if not (self.add_prefix_space or not is_split_into_words):
										raise Exception(
										    F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with"""
										    ''' pretokenized inputs.'''  )

								return super()._encode_plus(*snake_case_			,			**snake_case_  )







						def       __magic_name__							(							self					:      Optional[int]			,			snake_case_					:      str			,			snake_case_					:      Optional[str] = None  ):



								'''simple docstring'''



								snake_case__						:       Optional[Any]       						=  self._tokenizer.model.save(snake_case_			,			name=snake_case_  )
								return tuple(snake_case_  )







						def       __magic_name__							(							self					:      str			,			snake_case_					:      "Conversation"  ):



								'''simple docstring'''



								snake_case__						:       List[str]       						=  []
								for is_user, text in conversation.iter_texts():
										input_ids.extend(self.encode(snake_case_			,			add_special_tokens=snake_case_  ) + [self.eos_token_id]  )

								if len(snake_case_  ) > self.model_max_length:
										snake_case__						:       List[str]       						=  input_ids[-self.model_max_length :]
								return input_ids






'''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					:      Dict			,			snake_case_					:      Tuple			,			snake_case_					:      List[str]=1_3			,			snake_case_					:      Dict=7			,			snake_case_					:      int=True			,			snake_case_					:      Tuple=True			,			snake_case_					:      int=True			,			snake_case_					:      Any=True			,			snake_case_					:      Union[str, Any]=9_9			,			snake_case_					:      List[Any]=2_4			,			snake_case_					:      Optional[Any]=2			,			snake_case_					:      Union[str, Any]=6			,			snake_case_					:      Any=3_7			,			snake_case_					:      Any="gelu"			,			snake_case_					:      Dict=0.1			,			snake_case_					:      List[str]=0.1			,			snake_case_					:      Dict=5_1_2			,			snake_case_					:      Any=1_6			,			snake_case_					:      Optional[int]=2			,			snake_case_					:      Union[str, Any]=0.0_2			,			snake_case_					:      int=3			,			snake_case_					:      int=None			,			snake_case_					:      Union[str, Any]=1_0_0_0			,			):



								'''simple docstring'''



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







						def       __magic_name__							(							self					:      Union[str, Any]  ):



								'''simple docstring'''



								snake_case__						:       Any       						=  ids_tensor([self.batch_size, self.seq_length]			,			self.vocab_size  )

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

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

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

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

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

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







						def       __magic_name__							(							self					:      List[Any]  ):



								'''simple docstring'''



								return LiltConfig(
								    vocab_size=self.vocab_size			,			hidden_size=self.hidden_size			,			num_hidden_layers=self.num_hidden_layers			,			num_attention_heads=self.num_attention_heads			,			intermediate_size=self.intermediate_size			,			hidden_act=self.hidden_act			,			hidden_dropout_prob=self.hidden_dropout_prob			,			attention_probs_dropout_prob=self.attention_probs_dropout_prob			,			max_position_embeddings=self.max_position_embeddings			,			type_vocab_size=self.type_vocab_size			,			initializer_range=self.initializer_range			,			)







						def       __magic_name__							(							self					:      Optional[int]			,			snake_case_					:      Any			,			snake_case_					:      List[Any]			,			snake_case_					:      Union[str, Any]			,			snake_case_					:      str			,			snake_case_					:      Optional[Any]			,			snake_case_					:      Union[str, Any]			,			snake_case_					:      Tuple			,			):



								'''simple docstring'''



								snake_case__						:       Optional[Any]       						=  LiltModel(config=snake_case_  )
								model.to(snake_case_  )
								model.eval()
								snake_case__						:       Dict       						=  model(snake_case_			,			bbox=snake_case_			,			attention_mask=snake_case_			,			token_type_ids=snake_case_  )
								snake_case__						:       Optional[Any]       						=  model(snake_case_			,			bbox=snake_case_			,			token_type_ids=snake_case_  )
								snake_case__						:       Union[str, Any]       						=  model(snake_case_			,			bbox=snake_case_  )

								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       __magic_name__							(							self					:      Union[str, Any]			,			snake_case_					:      Union[str, Any]			,			snake_case_					:      Optional[Any]			,			snake_case_					:      List[Any]			,			snake_case_					:      Any			,			snake_case_					:      int			,			snake_case_					:      int			,			snake_case_					:      Tuple			,			):



								'''simple docstring'''



								snake_case__						:       List[Any]       						=  self.num_labels
								snake_case__						:       str       						=  LiltForTokenClassification(config=snake_case_  )
								model.to(snake_case_  )
								model.eval()
								snake_case__						:       List[Any]       						=  model(
								    snake_case_			,			bbox=snake_case_			,			attention_mask=snake_case_			,			token_type_ids=snake_case_			,			labels=snake_case_  )
								self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.seq_length, self.num_labels)  )







						def       __magic_name__							(							self					:      Dict			,			snake_case_					:      int			,			snake_case_					:      str			,			snake_case_					:      Union[str, Any]			,			snake_case_					:      Any			,			snake_case_					:      Union[str, Any]			,			snake_case_					:      Tuple			,			snake_case_					:      int			,			):



								'''simple docstring'''



								snake_case__						:       Optional[int]       						=  LiltForQuestionAnswering(config=snake_case_  )
								model.to(snake_case_  )
								model.eval()
								snake_case__						:       Optional[int]       						=  model(
								    snake_case_			,			bbox=snake_case_			,			attention_mask=snake_case_			,			token_type_ids=snake_case_			,			start_positions=snake_case_			,			end_positions=snake_case_			,			)
								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       __magic_name__							(							self					:      Union[str, Any]  ):



								'''simple docstring'''



								snake_case__						:       Dict       						=  self.prepare_config_and_inputs()
								(
								    (
								    snake_case__
								)						,       (
								    snake_case__
								)						,       (
								    snake_case__
								)						,       (
								    snake_case__
								)						,       (
								    snake_case__
								)						,       (
								    snake_case__
								)						,       (
								    snake_case__
								)						,       
								)						:       Tuple       						=  config_and_inputs
								snake_case__						:       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     a			(				SCREAMING_SNAKE_CASE			,			SCREAMING_SNAKE_CASE			,			SCREAMING_SNAKE_CASE			,			unittest.TestCase       ):






						"""simple docstring"""




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







						def       __magic_name__							(							self					:      List[str]			,			snake_case_					:      Union[str, Any]			,			snake_case_					:      Dict			,			snake_case_					:      Dict			,			snake_case_					:      str			,			snake_case_					:      Any  ):



								'''simple docstring'''



								return True







						def       __magic_name__							(							self					:      Dict  ):



								'''simple docstring'''



								snake_case__						:       List[Any]       						=  LiltModelTester(self  )
								snake_case__						:       Dict       						=  ConfigTester(self			,			config_class=snake_case_			,			hidden_size=3_7  )







						def       __magic_name__							(							self					:      List[str]  ):



								'''simple docstring'''



								self.config_tester.run_common_tests()







						def       __magic_name__							(							self					:      List[str]  ):



								'''simple docstring'''



								snake_case__						:       List[str]       						=  self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*snake_case_  )







						def       __magic_name__							(							self					:      Optional[Any]  ):



								'''simple docstring'''



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







						def       __magic_name__							(							self					:      Optional[int]  ):



								'''simple docstring'''



								snake_case__						:       Dict       						=  self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_token_classification(*snake_case_  )







						def       __magic_name__							(							self					:      Optional[Any]  ):



								'''simple docstring'''



								snake_case__						:       List[Any]       						=  self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_question_answering(*snake_case_  )







						@slow
						def       __magic_name__							(							self					:      str  ):



								'''simple docstring'''



								for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										snake_case__						:       List[str]       						=  LiltModel.from_pretrained(snake_case_  )
										self.assertIsNotNone(snake_case_  )





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






						"""simple docstring"""




						def       __magic_name__							(							self					:      List[str]  ):



								'''simple docstring'''



								snake_case__						:       Any       						=  LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base'''  ).to(snake_case_  )

								snake_case__						:       int       						=  torch.tensor([[1, 2]]			,			device=snake_case_  )
								snake_case__						:       List[str]       						=  torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]]			,			device=snake_case_  )

								# forward pass
								with torch.no_grad():
										snake_case__						:       Optional[int]       						=  model(input_ids=snake_case_			,			bbox=snake_case_  )

								snake_case__						:       Tuple       						=  torch.Size([1, 2, 7_6_8]  )
								snake_case__						:       Dict       						=  torch.tensor(
								    [[-0.0_6_5_3, 0.0_9_5_0, -0.0_0_6_1], [-0.0_5_4_5, 0.0_9_2_6, -0.0_3_2_4]]			,			device=snake_case_			,			)

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



