

import unittest

from transformers import LayoutLMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

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 (
			    LayoutLMForMaskedLM,
			    LayoutLMForQuestionAnswering,
			    LayoutLMForSequenceClassification,
			    LayoutLMForTokenClassification,
			    LayoutLMModel,
			)






class     lowerCamelCase_			:




	def __init__(    self	:    List[str]				,			__A	:    Union[str, Any]				,			__A	:    Optional[Any]=13				,			__A	:    str=7				,			__A	:    str=True				,			__A	:    int=True				,			__A	:    List[str]=True				,			__A	:    int=True				,			__A	:    int=99				,			__A	:    List[Any]=32				,			__A	:    str=5				,			__A	:    Tuple=4				,			__A	:    Optional[int]=37				,			__A	:    List[Any]="gelu"				,			__A	:    int=0.1				,			__A	:    str=0.1				,			__A	:    List[Any]=512				,			__A	:    int=16				,			__A	:    Dict=2				,			__A	:    Any=0.0_2				,			__A	:    List[Any]=3				,			__A	:    Dict=4				,			__A	:    int=None				,			__A	:    Optional[int]=1000				,			):
		__A   : Union[str, Any]								= parent
		__A   : Any								= batch_size
		__A   : Dict								= seq_length
		__A   : List[Any]								= is_training
		__A   : str								= use_input_mask
		__A   : Any								= use_token_type_ids
		__A   : Dict								= use_labels
		__A   : Any								= vocab_size
		__A   : Tuple								= hidden_size
		__A   : Union[str, Any]								= num_hidden_layers
		__A   : int								= num_attention_heads
		__A   : Dict								= intermediate_size
		__A   : str								= hidden_act
		__A   : List[str]								= hidden_dropout_prob
		__A   : Optional[int]								= attention_probs_dropout_prob
		__A   : str								= max_position_embeddings
		__A   : Any								= type_vocab_size
		__A   : List[str]								= type_sequence_label_size
		__A   : Optional[int]								= initializer_range
		__A   : Union[str, Any]								= num_labels
		__A   : Tuple								= num_choices
		__A   : Union[str, Any]								= scope
		__A   : str								= range_bbox




	def 					lowerCAmelCase_					(    self	:    Any       ):
		__A   : Optional[int]								= ids_tensor([self.batch_size, self.seq_length]				,			self.vocab_size       )

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

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

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

		__A   : List[str]								= None
		__A   : int								= None
		__A   : Dict								= None
		if self.use_labels:
			__A   : Any								= ids_tensor([self.batch_size]				,			self.type_sequence_label_size       )
			__A   : int								= ids_tensor([self.batch_size, self.seq_length]				,			self.num_labels       )
			__A   : Any								= ids_tensor([self.batch_size]				,			self.num_choices       )

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

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




	def 					lowerCAmelCase_					(    self	:    Dict       ):
		return LayoutLMConfig(
		    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 					lowerCAmelCase_					(    self	:    Any				,			__A	:    Optional[Any]				,			__A	:    Optional[Any]				,			__A	:    List[Any]				,			__A	:    str				,			__A	:    str				,			__A	:    List[str]				,			__A	:    str				,			__A	:    Union[str, Any]       ):
		__A   : List[Any]								= LayoutLMModel(config=__A       )
		model.to(__A       )
		model.eval()
		__A   : Tuple								= model(__A				,			__A				,			attention_mask=__A				,			token_type_ids=__A       )
		__A   : Tuple								= model(__A				,			__A				,			token_type_ids=__A       )
		__A   : Dict								= model(__A				,			__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 					lowerCAmelCase_					(    self	:    List[str]				,			__A	:    List[str]				,			__A	:    Optional[Any]				,			__A	:    List[Any]				,			__A	:    int				,			__A	:    Tuple				,			__A	:    Tuple				,			__A	:    List[Any]				,			__A	:    List[str]       ):
		__A   : int								= LayoutLMForMaskedLM(config=__A       )
		model.to(__A       )
		model.eval()
		__A   : Any								= model(__A				,			__A				,			attention_mask=__A				,			token_type_ids=__A				,			labels=__A       )
		self.parent.assertEqual(result.logits.shape				,			(self.batch_size, self.seq_length, self.vocab_size)       )




	def 					lowerCAmelCase_					(    self	:    Tuple				,			__A	:    List[Any]				,			__A	:    Optional[Any]				,			__A	:    int				,			__A	:    int				,			__A	:    Union[str, Any]				,			__A	:    int				,			__A	:    str				,			__A	:    Tuple       ):
		__A   : Optional[Any]								= self.num_labels
		__A   : str								= LayoutLMForSequenceClassification(__A       )
		model.to(__A       )
		model.eval()
		__A   : Optional[Any]								= model(
		    __A				,			__A				,			attention_mask=__A				,			token_type_ids=__A				,			labels=__A       )
		self.parent.assertEqual(result.logits.shape				,			(self.batch_size, self.num_labels)       )




	def 					lowerCAmelCase_					(    self	:    Tuple				,			__A	:    List[Any]				,			__A	:    Union[str, Any]				,			__A	:    Dict				,			__A	:    int				,			__A	:    Dict				,			__A	:    List[Any]				,			__A	:    Union[str, Any]				,			__A	:    List[str]       ):
		__A   : Tuple								= self.num_labels
		__A   : Tuple								= LayoutLMForTokenClassification(config=__A       )
		model.to(__A       )
		model.eval()
		__A   : Optional[int]								= model(__A				,			__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 					lowerCAmelCase_					(    self	:    Any				,			__A	:    List[str]				,			__A	:    int				,			__A	:    str				,			__A	:    Any				,			__A	:    Optional[int]				,			__A	:    Tuple				,			__A	:    Dict				,			__A	:    str       ):
		__A   : str								= LayoutLMForQuestionAnswering(config=__A       )
		model.to(__A       )
		model.eval()
		__A   : Dict								= 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 					lowerCAmelCase_					(    self	:    List[Any]       ):
		__A   : Optional[Any]								= self.prepare_config_and_inputs()
		(
		    __A							
		)   : List[Any]								= config_and_inputs
		__A   : Union[str, Any]								= {
		    """input_ids""": input_ids,
		    """bbox""": bbox,
		    """token_type_ids""": token_type_ids,
		    """attention_mask""": input_mask,
		}
		return config, inputs_dict






@require_torch
class     lowerCamelCase_			(  _lowercase	,			_lowercase	,			unittest.TestCase  ):
	_lowercase		:      Tuple    				=							(
	    (
	        LayoutLMModel,
	        LayoutLMForMaskedLM,
	        LayoutLMForSequenceClassification,
	        LayoutLMForTokenClassification,
	        LayoutLMForQuestionAnswering,
	    )
	    if is_torch_available()
	    else None
	)
	_lowercase		:      Tuple    				=							(
	    {
	        '''document-question-answering''': LayoutLMForQuestionAnswering,
	        '''feature-extraction''': LayoutLMModel,
	        '''fill-mask''': LayoutLMForMaskedLM,
	        '''text-classification''': LayoutLMForSequenceClassification,
	        '''token-classification''': LayoutLMForTokenClassification,
	        '''zero-shot''': LayoutLMForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	_lowercase		:      List[Any]    				=							True




	def 					lowerCAmelCase_					(    self	:    Optional[int]       ):
		__A   : List[str]								= LayoutLMModelTester(self       )
		__A   : Dict								= ConfigTester(self				,			config_class=__A				,			hidden_size=37       )




	def 					lowerCAmelCase_					(    self	:    int       ):
		self.config_tester.run_common_tests()




	def 					lowerCAmelCase_					(    self	:    Dict       ):
		__A   : Optional[Any]								= self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_model(*__A       )




	def 					lowerCAmelCase_					(    self	:    Any       ):
		__A   : str								= self.model_tester.prepare_config_and_inputs()
		for type in ["absolute", "relative_key", "relative_key_query"]:
			__A   : Tuple								= type
			self.model_tester.create_and_check_model(*__A       )




	def 					lowerCAmelCase_					(    self	:    Tuple       ):
		__A   : List[str]								= self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_for_masked_lm(*__A       )




	def 					lowerCAmelCase_					(    self	:    Optional[Any]       ):
		__A   : Dict								= self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_for_sequence_classification(*__A       )




	def 					lowerCAmelCase_					(    self	:    str       ):
		__A   : int								= self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_for_token_classification(*__A       )




	def 					lowerCAmelCase_					(    self	:    List[Any]       ):
		__A   : List[str]								= self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_for_question_answering(*__A       )




	@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""       )
	def 					lowerCAmelCase_					(    self	:    Union[str, Any]       ):
		pass






def        __SCREAMING_SNAKE_CASE    (      )				->							Union[str, Any]:
	# Here we prepare a batch of 2 sequences to test a LayoutLM forward pass on:
	# fmt: off
	__A   : List[Any]								= torch.tensor([[101,1019,1014,1016,1037,12849,4747,1004,14246,2278,5439,4524,5002,2930,2193,2930,4341,3208,1005,1055,2171,2848,11300,3531,102],[101,4070,4034,7020,1024,3058,1015,1013,2861,1013,6070,19274,2772,6205,27814,16147,16147,4343,2047,10283,10969,14389,1012,2338,102]] ,device=a__					)  # noqa: E231
	__A   : List[str]								= torch.tensor([[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, 1, 1, 1, 1, 1],] ,device=a__					)  # noqa: E231
	__A   : Tuple								= torch.tensor([[[0,0,0,0],[423,237,440,251],[427,272,441,287],[419,115,437,129],[961,885,992,912],[256,38,330,58],[256,38,330,58],[336,42,353,57],[360,39,401,56],[360,39,401,56],[411,39,471,59],[479,41,528,59],[533,39,630,60],[67,113,134,131],[141,115,209,132],[68,149,133,166],[141,149,187,164],[195,148,287,165],[195,148,287,165],[195,148,287,165],[295,148,349,165],[441,149,492,166],[497,149,546,164],[64,201,125,218],[1000,1000,1000,1000]],[[0,0,0,0],[662,150,754,166],[665,199,742,211],[519,213,554,228],[519,213,554,228],[134,433,187,454],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[314,469,376,482],[504,684,582,706],[941,825,973,900],[941,825,973,900],[941,825,973,900],[941,825,973,900],[610,749,652,765],[130,659,168,672],[176,657,237,672],[238,657,312,672],[443,653,628,672],[443,653,628,672],[716,301,825,317],[1000,1000,1000,1000]]] ,device=a__					)  # noqa: E231
	__A   : List[str]								= torch.tensor([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]] ,device=a__					)  # noqa: E231
	# these are sequence labels (i.e. at the token level)
	__A   : int								= torch.tensor([[-100,10,10,10,9,1,-100,7,7,-100,7,7,4,2,5,2,8,8,-100,-100,5,0,3,2,-100],[-100,12,12,12,-100,12,10,-100,-100,-100,-100,10,12,9,-100,-100,-100,10,10,10,9,12,-100,10,-100]] ,device=a__					)  # noqa: E231
	# fmt: on

	return input_ids, attention_mask, bbox, token_type_ids, labels







@require_torch
class     lowerCamelCase_			(  unittest.TestCase  ):




	@slow
	def 					lowerCAmelCase_					(    self	:    Tuple       ):
		__A   : List[str]								= LayoutLMModel.from_pretrained("""microsoft/layoutlm-base-uncased"""       ).to(__A       )

		__A   : str								= prepare_layoutlm_batch_inputs()

		# forward pass
		__A   : int								= model(input_ids=__A				,			bbox=__A				,			attention_mask=__A				,			token_type_ids=__A       )

		# test the sequence output on [0, :3, :3]
		__A   : Any								= torch.tensor(
		    [[0.1_7_8_5, -0.1_9_4_7, -0.0_4_2_5], [-0.3_2_5_4, -0.2_8_0_7, 0.2_5_5_3], [-0.5_3_9_1, -0.3_3_2_2, 0.3_3_6_4]]				,			device=__A				,			)

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

		# test the pooled output on [1, :3]
		__A   : Tuple								= torch.tensor([-0.6_5_8_0, -0.0_2_1_4, 0.8_5_5_2]				,			device=__A       )

		self.assertTrue(torch.allclose(outputs.pooler_output[1, :3]				,			__A				,			atol=1e-3       )       )




	@slow
	def 					lowerCAmelCase_					(    self	:    str       ):
		# initialize model with randomly initialized sequence classification head
		__A   : int								= LayoutLMForSequenceClassification.from_pretrained("""microsoft/layoutlm-base-uncased"""				,			num_labels=2       ).to(
		    __A       )

		__A   : Optional[int]								= prepare_layoutlm_batch_inputs()

		# forward pass
		__A   : Any								= model(
		    input_ids=__A				,			bbox=__A				,			attention_mask=__A				,			token_type_ids=__A				,			labels=torch.tensor([1, 1]				,			device=__A       )				,			)

		# test whether we get a loss as a scalar
		__A   : Optional[int]								= outputs.loss
		__A   : List[str]								= torch.Size([]       )
		self.assertEqual(loss.shape				,			__A       )

		# test the shape of the logits
		__A   : Tuple								= outputs.logits
		__A   : Union[str, Any]								= torch.Size((2, 2)       )
		self.assertEqual(logits.shape				,			__A       )




	@slow
	def 					lowerCAmelCase_					(    self	:    Tuple       ):
		# initialize model with randomly initialized token classification head
		__A   : int								= LayoutLMForTokenClassification.from_pretrained("""microsoft/layoutlm-base-uncased"""				,			num_labels=13       ).to(
		    __A       )

		__A   : Dict								= prepare_layoutlm_batch_inputs()

		# forward pass
		__A   : Optional[int]								= model(
		    input_ids=__A				,			bbox=__A				,			attention_mask=__A				,			token_type_ids=__A				,			labels=__A       )

		# test the loss calculation to be around 2.65
		# expected_loss = torch.tensor(2.65, device=torch_device)

		# The loss is currently somewhat random and can vary between 0.1-0.3 atol.
		# self.assertTrue(torch.allclose(outputs.loss, expected_loss, atol=0.1))

		# test the shape of the logits
		__A   : Optional[Any]								= outputs.logits
		__A   : Union[str, Any]								= torch.Size((2, 25, 13)       )
		self.assertEqual(logits.shape				,			__A       )




	@slow
	def 					lowerCAmelCase_					(    self	:    Optional[Any]       ):
		# initialize model with randomly initialized token classification head
		__A   : Optional[Any]								= LayoutLMForQuestionAnswering.from_pretrained("""microsoft/layoutlm-base-uncased"""       ).to(__A       )

		__A   : str								= prepare_layoutlm_batch_inputs()

		# forward pass
		__A   : Dict								= model(input_ids=__A				,			bbox=__A				,			attention_mask=__A				,			token_type_ids=__A       )

		# test the shape of the logits
		__A   : Optional[int]								= torch.Size((2, 25)       )
		self.assertEqual(outputs.start_logits.shape				,			__A       )
		self.assertEqual(outputs.end_logits.shape				,			__A       )








import math






class     lowerCamelCase_			:




	def __init__(    self	:    Dict				,			__A	:    int				,			__A	:    int				,			__A	:    int				,			__A	:    Any       ):
		__A   : Union[str, Any]								= x
		__A   : Union[str, Any]								= y
		__A   : Optional[int]								= step_size
		__A   : Dict								= function_to_optimize




	def 					lowerCAmelCase_					(    self	:    Optional[int]       ):
		return self.function(self.x				,			self.y       )




	def 					lowerCAmelCase_					(    self	:    int       ):
		__A   : Dict								= self.step_size
		return [
		    SearchProblem(__A				,			__A				,			__A				,			self.function       )
		    for x, y in (
		        (self.x - step_size, self.y - step_size),
		        (self.x - step_size, self.y),
		        (self.x - step_size, self.y + step_size),
		        (self.x, self.y - step_size),
		        (self.x, self.y + step_size),
		        (self.x + step_size, self.y - step_size),
		        (self.x + step_size, self.y),
		        (self.x + step_size, self.y + step_size),
		    )
		]




	def __hash__(    self	:    str       ):
		return hash(str(self       )       )




	def __eq__(    self	:    Union[str, Any]				,			__A	:    Optional[int]       ):
		if isinstance(__A				,			__A       ):
			return hash(str(self       )       ) == hash(str(__A       )       )
		return False




	def __str__(    self	:    List[Any]       ):
		return F"""x: {self.x} y: {self.y}"""






def        __SCREAMING_SNAKE_CASE    (      a__						:      Optional[Any] ,a__						:      bool = True ,a__						:      float = math.inf ,a__						:      float = -math.inf ,a__						:      float = math.inf ,a__						:      float = -math.inf ,a__						:      bool = False ,a__						:      int = 10000 ,)				->							SearchProblem:
	__A   : int								= search_prob
	__A   : List[str]								= []  # list to store the current score at each iteration
	__A   : Optional[Any]								= 0
	__A   : Any								= False
	__A   : Dict								= set()
	while not solution_found and iterations < max_iter:
		visited.add(a__					)
		iterations += 1
		__A   : Union[str, Any]								= current_state.score()
		scores.append(a__					)
		__A   : List[Any]								= current_state.get_neighbors()
		__A   : Tuple								= -math.inf
		__A   : str								= math.inf
		__A   : Optional[int]								= None  # to hold the next best neighbor
		for neighbor in neighbors:
			if neighbor in visited:
				continue  # do not want to visit the same state again
			if (
			    neighbor.x > max_x
			    or neighbor.x < min_x
			    or neighbor.y > max_y
			    or neighbor.y < min_y
			):
				continue  # neighbor outside our bounds
			__A   : int								= neighbor.score() - current_score
			if find_max:  # finding max
				# going to direction with greatest ascent
				if change > max_change and change > 0:
					__A   : str								= change
					__A   : Optional[int]								= neighbor
			else:  # finding min
				# to direction with greatest descent
				if change < min_change and change < 0:
					__A   : List[Any]								= change
					__A   : List[str]								= neighbor
		if next_state is not None:
			# we found at least one neighbor which improved the current state
			__A   : Tuple								= next_state
		else:
			# since we have no neighbor that improves the solution we stop the search
			__A   : str								= True

	if visualization:
		from matplotlib import pyplot as plt

		plt.plot(range(a__					) ,a__					)
		plt.xlabel("""Iterations"""					)
		plt.ylabel("""Function values"""					)
		plt.show()

	return current_state


if __name__ == "__main__":
			import doctest

			doctest.testmod()
			def        __SCREAMING_SNAKE_CASE    (      a__						:      str ,a__						:      Any					)				->							Dict:
				return (x**2) + (y**2)

			# starting the problem with initial coordinates (3, 4)
			UpperCAmelCase_       :				Tuple		   =      SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa)
			UpperCAmelCase_       :				Any		   =      hill_climbing(prob, find_max=False)
			print(
			    '''The minimum score for f(x, y) = x^2 + y^2 found via hill climbing: '''
			    f"""{local_min.score()}"""
			)

			# starting the problem with initial coordinates (12, 47)
			UpperCAmelCase_       :				List[Any]		   =      SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa)
			UpperCAmelCase_       :				Any		   =      hill_climbing(
			    prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True
			)
			print(
			    '''The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 '''
			    f"""and 50 > y > - 5 found via hill climbing: {local_min.score()}"""
			)
			def        __SCREAMING_SNAKE_CASE    (      a__						:      int ,a__						:      List[str]					)				->							Any:
				return (3 * x**2) - (6 * y)

			UpperCAmelCase_       :				Tuple		   =      SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa)
			UpperCAmelCase_       :				Dict		   =      hill_climbing(prob, find_max=True)







			print(
			    '''The maximum score for f(x, y) = x^2 + y^2 found via hill climbing: '''
			    f"""{local_min.score()}"""
			)





