


"""simple docstring"""
import unittest

import numpy as np

from transformers import AlbertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
			import jax.numpy as jnp

			from transformers.models.albert.modeling_flax_albert import (
			    FlaxAlbertForMaskedLM,
			    FlaxAlbertForMultipleChoice,
			    FlaxAlbertForPreTraining,
			    FlaxAlbertForQuestionAnswering,
			    FlaxAlbertForSequenceClassification,
			    FlaxAlbertForTokenClassification,
			    FlaxAlbertModel,
			)



class 			_UpperCAmelCase (							unittest.TestCase				):






		'''simple docstring'''

		def __init__(self				,       a_				,       a_=13				,       a_=7				,       a_=True				,       a_=True				,       a_=True				,       a_=True				,       a_=99				,       a_=32				,       a_=5				,       a_=4				,       a_=37				,       a_="gelu"				,       a_=0.1				,       a_=0.1				,       a_=5_12				,       a_=16				,       a_=2				,       a_=0.02				,       a_=4				,       ):





			'''simple docstring'''

			__snake_case	:						Union[str, Any]						=				parent
			__snake_case	:						Dict						=				batch_size
			__snake_case	:						Optional[int]						=				seq_length
			__snake_case	:						Tuple						=				is_training
			__snake_case	:						Optional[int]						=				use_attention_mask
			__snake_case	:						Dict						=				use_token_type_ids
			__snake_case	:						Dict						=				use_labels
			__snake_case	:						Tuple						=				vocab_size
			__snake_case	:						Tuple						=				hidden_size
			__snake_case	:						List[str]						=				num_hidden_layers
			__snake_case	:						Dict						=				num_attention_heads
			__snake_case	:						Optional[int]						=				intermediate_size
			__snake_case	:						Any						=				hidden_act
			__snake_case	:						Union[str, Any]						=				hidden_dropout_prob
			__snake_case	:						Union[str, Any]						=				attention_probs_dropout_prob
			__snake_case	:						Dict						=				max_position_embeddings
			__snake_case	:						str						=				type_vocab_size
			__snake_case	:						List[Any]						=				type_sequence_label_size
			__snake_case	:						Optional[int]						=				initializer_range
			__snake_case	:						Any						=				num_choices



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Union[str, Any]						=				ids_tensor([self.batch_size, self.seq_length]				,       self.vocab_size					)

			__snake_case	:						Union[str, Any]						=				None
			if self.use_attention_mask:
				__snake_case	:						Tuple						=				random_attention_mask([self.batch_size, self.seq_length]					)

			__snake_case	:						Optional[Any]						=				None
			if self.use_token_type_ids:
				__snake_case	:						List[Any]						=				ids_tensor([self.batch_size, self.seq_length]				,       self.type_vocab_size					)

			__snake_case	:						Tuple						=				AlbertConfig(
			    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				,       is_decoder=a_				,       initializer_range=self.initializer_range				,       )

			return config, input_ids, token_type_ids, attention_mask



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Dict						=				self.prepare_config_and_inputs()
			__snake_case	,							__snake_case	,							__snake_case	,							__snake_case	:						Optional[Any]						=				config_and_inputs
			__snake_case	:						Any						=				{'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask}
			return config, inputs_dict



@require_flax
class 			_UpperCAmelCase (							__snake_case,				unittest.TestCase				):






		'''simple docstring'''

		lowerCamelCase__				=(
		    (
		        FlaxAlbertModel,
		        FlaxAlbertForPreTraining,
		        FlaxAlbertForMaskedLM,
		        FlaxAlbertForMultipleChoice,
		        FlaxAlbertForQuestionAnswering,
		        FlaxAlbertForSequenceClassification,
		        FlaxAlbertForTokenClassification,
		        FlaxAlbertForQuestionAnswering,
		    )
		    if is_flax_available()
		    else ()
		)



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Dict						=				FlaxAlbertModelTester(self					)



		@slow
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			for model_class_name in self.all_model_classes:
				__snake_case	:						Union[str, Any]						=				model_class_name.from_pretrained('''albert-base-v2'''					)
				__snake_case	:						Tuple						=				model(np.ones((1, 1)					)					)
				self.assertIsNotNone(a_					)



@require_flax
class 			_UpperCAmelCase (							unittest.TestCase				):






		'''simple docstring'''

		@slow
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Tuple						=				FlaxAlbertModel.from_pretrained('''albert-base-v2'''					)
			__snake_case	:						List[str]						=				np.array([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]]					)
			__snake_case	:						Tuple						=				np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]					)
			__snake_case	:						Dict						=				model(a_				,       attention_mask=a_					)[0]
			__snake_case	:						Dict						=				(1, 11, 7_68)
			self.assertEqual(output.shape				,       a_					)
			__snake_case	:						int						=				np.array(
			    [[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]]					)

			self.assertTrue(jnp.allclose(output[:, 1:4, 1:4]				,       a_				,       atol=1E-4					)					)










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))
