



'''simple docstring'''




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


   '''simple docstring'''

   def __init__(							self					:			Any							,					lowerCAmelCase__					:			Dict							,					lowerCAmelCase__					:			Union[str, Any]=1_3							,					lowerCAmelCase__					:			Optional[int]=7							,					lowerCAmelCase__					:			Optional[int]=True							,					lowerCAmelCase__					:			List[str]=True							,					lowerCAmelCase__					:			Union[str, Any]=True							,					lowerCAmelCase__					:			int=True							,					lowerCAmelCase__					:			Any=9_9							,					lowerCAmelCase__					:			Optional[int]=3_2							,					lowerCAmelCase__					:			str=5							,					lowerCAmelCase__					:			Tuple=4							,					lowerCAmelCase__					:			int=3_7							,					lowerCAmelCase__					:			Any="gelu"							,					lowerCAmelCase__					:			Optional[int]=0.1							,					lowerCAmelCase__					:			List[str]=0.1							,					lowerCAmelCase__					:			Dict=5_1_2							,					lowerCAmelCase__					:			List[Any]=1_6							,					lowerCAmelCase__					:			int=2							,					lowerCAmelCase__					:			int=0.02							,					lowerCAmelCase__					:			str=3							,					lowerCAmelCase__					:			Optional[int]=4							,					lowerCAmelCase__					:			List[str]=None							,					lowerCAmelCase__					:			List[str]=1_0_0_0							,					):





     """simple docstring"""






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

   def UpperCamelCase__ (							self					:			List[Any]						):





     """simple docstring"""






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

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

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

     __SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		None
     if self.use_token_type_ids:
       __SCREAMING_SNAKE_CASE	:		str   	=		ids_tensor([self.batch_size, self.seq_length]							,					self.type_vocab_size						)

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

     __SCREAMING_SNAKE_CASE	:		Tuple   	=		self.get_config()

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

   def UpperCamelCase__ (							self					:			List[Any]						):





     """simple docstring"""






     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 UpperCamelCase__ (							self					:			Union[str, Any]							,					lowerCAmelCase__					:			Dict							,					lowerCAmelCase__					:			str							,					lowerCAmelCase__					:			int							,					lowerCAmelCase__					:			Optional[int]							,					lowerCAmelCase__					:			List[Any]							,					lowerCAmelCase__					:			List[str]							,					lowerCAmelCase__					:			List[Any]							,					lowerCAmelCase__					:			int						):





     """simple docstring"""






     __SCREAMING_SNAKE_CASE	:		Dict   	=		LayoutLMModel(config=lowerCAmelCase__						)
     model.to(lowerCAmelCase__						)
     model.eval()
     __SCREAMING_SNAKE_CASE	:		Dict   	=		model(lowerCAmelCase__							,					lowerCAmelCase__							,					attention_mask=lowerCAmelCase__							,					token_type_ids=lowerCAmelCase__						)
     __SCREAMING_SNAKE_CASE	:		Optional[int]   	=		model(lowerCAmelCase__							,					lowerCAmelCase__							,					token_type_ids=lowerCAmelCase__						)
     __SCREAMING_SNAKE_CASE	:		Dict   	=		model(lowerCAmelCase__							,					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					:			List[Any]							,					lowerCAmelCase__					:			Tuple							,					lowerCAmelCase__					:			Optional[Any]							,					lowerCAmelCase__					:			Optional[Any]							,					lowerCAmelCase__					:			Dict							,					lowerCAmelCase__					:			Optional[int]							,					lowerCAmelCase__					:			Any							,					lowerCAmelCase__					:			List[str]							,					lowerCAmelCase__					:			Dict						):





     """simple docstring"""






     __SCREAMING_SNAKE_CASE	:		Optional[int]   	=		LayoutLMForMaskedLM(config=lowerCAmelCase__						)
     model.to(lowerCAmelCase__						)
     model.eval()
     __SCREAMING_SNAKE_CASE	:		int   	=		model(lowerCAmelCase__							,					lowerCAmelCase__							,					attention_mask=lowerCAmelCase__							,					token_type_ids=lowerCAmelCase__							,					labels=lowerCAmelCase__						)
     self.parent.assertEqual(result.logits.shape							,					(self.batch_size, self.seq_length, self.vocab_size)						)

   def UpperCamelCase__ (							self					:			List[Any]							,					lowerCAmelCase__					:			int							,					lowerCAmelCase__					:			int							,					lowerCAmelCase__					:			Optional[Any]							,					lowerCAmelCase__					:			int							,					lowerCAmelCase__					:			Optional[int]							,					lowerCAmelCase__					:			List[str]							,					lowerCAmelCase__					:			List[str]							,					lowerCAmelCase__					:			Any						):





     """simple docstring"""






     __SCREAMING_SNAKE_CASE	:		Any   	=		self.num_labels
     __SCREAMING_SNAKE_CASE	:		str   	=		LayoutLMForSequenceClassification(lowerCAmelCase__						)
     model.to(lowerCAmelCase__						)
     model.eval()
     __SCREAMING_SNAKE_CASE	:		Tuple   	=		model(
         lowerCAmelCase__							,					lowerCAmelCase__							,					attention_mask=lowerCAmelCase__							,					token_type_ids=lowerCAmelCase__							,					labels=lowerCAmelCase__						)
     self.parent.assertEqual(result.logits.shape							,					(self.batch_size, self.num_labels)						)

   def UpperCamelCase__ (							self					:			List[Any]							,					lowerCAmelCase__					:			Tuple							,					lowerCAmelCase__					:			Any							,					lowerCAmelCase__					:			Optional[Any]							,					lowerCAmelCase__					:			Union[str, Any]							,					lowerCAmelCase__					:			Union[str, Any]							,					lowerCAmelCase__					:			List[Any]							,					lowerCAmelCase__					:			int							,					lowerCAmelCase__					:			List[Any]						):





     """simple docstring"""






     __SCREAMING_SNAKE_CASE	:		Dict   	=		self.num_labels
     __SCREAMING_SNAKE_CASE	:		List[str]   	=		LayoutLMForTokenClassification(config=lowerCAmelCase__						)
     model.to(lowerCAmelCase__						)
     model.eval()
     __SCREAMING_SNAKE_CASE	:		List[str]   	=		model(lowerCAmelCase__							,					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					:			Optional[int]							,					lowerCAmelCase__					:			int							,					lowerCAmelCase__					:			Union[str, Any]							,					lowerCAmelCase__					:			Optional[Any]							,					lowerCAmelCase__					:			str							,					lowerCAmelCase__					:			Tuple							,					lowerCAmelCase__					:			str							,					lowerCAmelCase__					:			Tuple							,					lowerCAmelCase__					:			Dict						):





     """simple docstring"""






     __SCREAMING_SNAKE_CASE	:		str   	=		LayoutLMForQuestionAnswering(config=lowerCAmelCase__						)
     model.to(lowerCAmelCase__						)
     model.eval()
     __SCREAMING_SNAKE_CASE	:		int   	=		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					:			List[Any]						):





     """simple docstring"""






     __SCREAMING_SNAKE_CASE	:		int   	=		self.prepare_config_and_inputs()
     (
         __SCREAMING_SNAKE_CASE  
     )	:		Union[str, Any]   	=		config_and_inputs
     __SCREAMING_SNAKE_CASE	:		Tuple   	=		{
         "input_ids": input_ids,
         "bbox": bbox,
         "token_type_ids": token_type_ids,
         "attention_mask": input_mask,
     }
     return config, inputs_dict






@require_torch
class 						_UpperCamelCase  (							snake_case__   , snake_case__   , unittest.TestCase   ):


   '''simple docstring'''

   _A				:		Optional[int]         =		(
       (
           LayoutLMModel,
           LayoutLMForMaskedLM,
           LayoutLMForSequenceClassification,
           LayoutLMForTokenClassification,
           LayoutLMForQuestionAnswering,
       )
       if is_torch_available()
       else None
   )
   _A				:		Union[str, Any]         =		(
       {
           "document-question-answering": LayoutLMForQuestionAnswering,
           "feature-extraction": LayoutLMModel,
           "fill-mask": LayoutLMForMaskedLM,
           "text-classification": LayoutLMForSequenceClassification,
           "token-classification": LayoutLMForTokenClassification,
           "zero-shot": LayoutLMForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )
   _A				:		Union[str, Any]         =		True

   def UpperCamelCase__ (							self					:			Tuple						):





     """simple docstring"""






     __SCREAMING_SNAKE_CASE	:		Optional[int]   	=		LayoutLMModelTester(self						)
     __SCREAMING_SNAKE_CASE	:		Any   	=		ConfigTester(self							,					config_class=lowerCAmelCase__							,					hidden_size=3_7						)

   def UpperCamelCase__ (							self					:			List[str]						):





     """simple docstring"""






     self.config_tester.run_common_tests()

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





     """simple docstring"""






     __SCREAMING_SNAKE_CASE	:		Tuple   	=		self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowerCAmelCase__						)

   def UpperCamelCase__ (							self					:			Optional[Any]						):





     """simple docstring"""






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

   def UpperCamelCase__ (							self					:			str						):





     """simple docstring"""






     __SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_masked_lm(*lowerCAmelCase__						)

   def UpperCamelCase__ (							self					:			List[Any]						):





     """simple docstring"""






     __SCREAMING_SNAKE_CASE	:		Dict   	=		self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_sequence_classification(*lowerCAmelCase__						)

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





     """simple docstring"""






     __SCREAMING_SNAKE_CASE	:		List[Any]   	=		self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_token_classification(*lowerCAmelCase__						)

   def UpperCamelCase__ (							self					:			Any						):





     """simple docstring"""






     __SCREAMING_SNAKE_CASE	:		Tuple   	=		self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_question_answering(*lowerCAmelCase__						)



   @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""						)
   def UpperCamelCase__ (							self					:			List[Any]						):





     """simple docstring"""






     pass


def     lowerCAmelCase_       (     ):
  __SCREAMING_SNAKE_CASE	:		Dict   	=		torch.tensor([[1_01,10_19,10_14,10_16,10_37,1_28_49,47_47,10_04,1_42_46,22_78,54_39,45_24,50_02,29_30,21_93,29_30,43_41,32_08,10_05,10_55,21_71,28_48,1_13_00,35_31,1_02],[1_01,40_70,40_34,70_20,10_24,30_58,10_15,10_13,28_61,10_13,60_70,1_92_74,27_72,62_05,2_78_14,1_61_47,1_61_47,43_43,20_47,1_02_83,1_09_69,1_43_89,10_12,23_38,1_02]]	,				device=_UpperCAmelCase )  # noqa: E231
  __SCREAMING_SNAKE_CASE	:		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=_UpperCAmelCase )  # noqa: E231
  __SCREAMING_SNAKE_CASE	:		Dict   	=		torch.tensor([[[0,0,0,0],[4_23,2_37,4_40,2_51],[4_27,2_72,4_41,2_87],[4_19,1_15,4_37,1_29],[9_61,8_85,9_92,9_12],[2_56,38,3_30,58],[2_56,38,3_30,58],[3_36,42,3_53,57],[3_60,39,4_01,56],[3_60,39,4_01,56],[4_11,39,4_71,59],[4_79,41,5_28,59],[5_33,39,6_30,60],[67,1_13,1_34,1_31],[1_41,1_15,2_09,1_32],[68,1_49,1_33,1_66],[1_41,1_49,1_87,1_64],[1_95,1_48,2_87,1_65],[1_95,1_48,2_87,1_65],[1_95,1_48,2_87,1_65],[2_95,1_48,3_49,1_65],[4_41,1_49,4_92,1_66],[4_97,1_49,5_46,1_64],[64,2_01,1_25,2_18],[10_00,10_00,10_00,10_00]],[[0,0,0,0],[6_62,1_50,7_54,1_66],[6_65,1_99,7_42,2_11],[5_19,2_13,5_54,2_28],[5_19,2_13,5_54,2_28],[1_34,4_33,1_87,4_54],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[3_14,4_69,3_76,4_82],[5_04,6_84,5_82,7_06],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[6_10,7_49,6_52,7_65],[1_30,6_59,1_68,6_72],[1_76,6_57,2_37,6_72],[2_38,6_57,3_12,6_72],[4_43,6_53,6_28,6_72],[4_43,6_53,6_28,6_72],[7_16,3_01,8_25,3_17],[10_00,10_00,10_00,10_00]]]	,				device=_UpperCAmelCase )  # noqa: E231
  __SCREAMING_SNAKE_CASE	:		int   	=		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=_UpperCAmelCase )  # noqa: E231
  # these are sequence labels (i.e. at the token level)
  __SCREAMING_SNAKE_CASE	:		Optional[int]   	=		torch.tensor([[-1_00,10,10,10,9,1,-1_00,7,7,-1_00,7,7,4,2,5,2,8,8,-1_00,-1_00,5,0,3,2,-1_00],[-1_00,12,12,12,-1_00,12,10,-1_00,-1_00,-1_00,-1_00,10,12,9,-1_00,-1_00,-1_00,10,10,10,9,12,-1_00,10,-1_00]]	,				device=_UpperCAmelCase )  # noqa: E231
  # fmt: on

  return input_ids, attention_mask, bbox, token_type_ids, labels






@require_torch
class 						_UpperCamelCase  (							unittest.TestCase   ):


   '''simple docstring'''

   @slow
   def UpperCamelCase__ (							self					:			Optional[Any]						):





     """simple docstring"""






     __SCREAMING_SNAKE_CASE	:		List[Any]   	=		LayoutLMModel.from_pretrained("""microsoft/layoutlm-base-uncased"""						).to(lowerCAmelCase__						)

     __SCREAMING_SNAKE_CASE	:		List[Any]   	=		prepare_layoutlm_batch_inputs()

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

     # test the sequence output on [0, :3, :3]
     __SCREAMING_SNAKE_CASE	:		List[str]   	=		torch.tensor(
         [[0.17_85, -0.19_47, -0.04_25], [-0.32_54, -0.28_07, 0.25_53], [-0.53_91, -0.33_22, 0.33_64]]							,					device=lowerCAmelCase__							,					)

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

     # test the pooled output on [1, :3]
     __SCREAMING_SNAKE_CASE	:		int   	=		torch.tensor([-0.65_80, -0.02_14, 0.85_52]							,					device=lowerCAmelCase__						)

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

   @slow
   def UpperCamelCase__ (							self					:			List[Any]						):





     """simple docstring"""






     __SCREAMING_SNAKE_CASE	:		List[Any]   	=		LayoutLMForSequenceClassification.from_pretrained("""microsoft/layoutlm-base-uncased"""							,					num_labels=2						).to(
         lowerCAmelCase__						)

     __SCREAMING_SNAKE_CASE	:		int   	=		prepare_layoutlm_batch_inputs()

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

     # test whether we get a loss as a scalar
     __SCREAMING_SNAKE_CASE	:		Dict   	=		outputs.loss
     __SCREAMING_SNAKE_CASE	:		str   	=		torch.Size([]						)
     self.assertEqual(loss.shape							,					lowerCAmelCase__						)

     # test the shape of the logits
     __SCREAMING_SNAKE_CASE	:		int   	=		outputs.logits
     __SCREAMING_SNAKE_CASE	:		str   	=		torch.Size((2, 2)						)
     self.assertEqual(logits.shape							,					lowerCAmelCase__						)

   @slow
   def UpperCamelCase__ (							self					:			Tuple						):





     """simple docstring"""






     __SCREAMING_SNAKE_CASE	:		Dict   	=		LayoutLMForTokenClassification.from_pretrained("""microsoft/layoutlm-base-uncased"""							,					num_labels=1_3						).to(
         lowerCAmelCase__						)

     __SCREAMING_SNAKE_CASE	:		Dict   	=		prepare_layoutlm_batch_inputs()

     # forward pass
     __SCREAMING_SNAKE_CASE	:		str   	=		model(
         input_ids=lowerCAmelCase__							,					bbox=lowerCAmelCase__							,					attention_mask=lowerCAmelCase__							,					token_type_ids=lowerCAmelCase__							,					labels=lowerCAmelCase__						)

     # 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
     __SCREAMING_SNAKE_CASE	:		int   	=		outputs.logits
     __SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		torch.Size((2, 2_5, 1_3)						)
     self.assertEqual(logits.shape							,					lowerCAmelCase__						)



   @slow
   def UpperCamelCase__ (							self					:			Optional[int]						):





     """simple docstring"""






     __SCREAMING_SNAKE_CASE	:		str   	=		LayoutLMForQuestionAnswering.from_pretrained("""microsoft/layoutlm-base-uncased"""						).to(lowerCAmelCase__						)

     __SCREAMING_SNAKE_CASE	:		Tuple   	=		prepare_layoutlm_batch_inputs()

     # forward pass
     __SCREAMING_SNAKE_CASE	:		Tuple   	=		model(input_ids=lowerCAmelCase__							,					bbox=lowerCAmelCase__							,					attention_mask=lowerCAmelCase__							,					token_type_ids=lowerCAmelCase__						)

     # test the shape of the logits
     __SCREAMING_SNAKE_CASE	:		List[str]   	=		torch.Size((2, 2_5)						)
     self.assertEqual(outputs.start_logits.shape							,					lowerCAmelCase__						)
     self.assertEqual(outputs.end_logits.shape							,					lowerCAmelCase__						)




'''simple docstring'''




import math
from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


UpperCamelCase__	:     List[str]    =			logging.get_logger(__name__)  # pylint: disable=invalid-name

UpperCamelCase__	:     Tuple    =			'''
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif

        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

        >>> repo = "openai/shap-e"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 15.0
        >>> prompt = "a shark"

        >>> images = pipe(
        ...     prompt,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], "shark_3d.gif")
        ```
'''






@dataclass
class 						_UpperCamelCase  (							lowerCamelCase__   ):


			'''simple docstring'''

			_A				:		Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]






class 						_UpperCamelCase  (							lowerCamelCase__   ):


			'''simple docstring'''

			def __init__(							self					:			List[str]							,					lowerCAmelCase__					:			PriorTransformer							,					lowerCAmelCase__					:			CLIPTextModelWithProjection							,					lowerCAmelCase__					:			CLIPTokenizer							,					lowerCAmelCase__					:			HeunDiscreteScheduler							,					lowerCAmelCase__					:			ShapERenderer							,					):





					"""simple docstring"""






					super().__init__()

					self.register_modules(
					    prior=lowerCAmelCase__							,					text_encoder=lowerCAmelCase__							,					tokenizer=lowerCAmelCase__							,					scheduler=lowerCAmelCase__							,					renderer=lowerCAmelCase__							,					)

			def UpperCamelCase__ (							self					:			Tuple							,					lowerCAmelCase__					:			List[Any]							,					lowerCAmelCase__					:			List[str]							,					lowerCAmelCase__					:			Any							,					lowerCAmelCase__					:			Dict							,					lowerCAmelCase__					:			List[Any]							,					lowerCAmelCase__					:			int						):





					"""simple docstring"""






					if latents is None:
							__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		randn_tensor(lowerCAmelCase__							,					generator=lowerCAmelCase__							,					device=lowerCAmelCase__							,					dtype=lowerCAmelCase__						)
					else:
							if latents.shape != shape:
									raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}"						)
							__SCREAMING_SNAKE_CASE	:		Any   	=		latents.to(lowerCAmelCase__						)

					__SCREAMING_SNAKE_CASE	:		Dict   	=		latents * scheduler.init_noise_sigma
					return latents

			def UpperCamelCase__ (							self					:			str							,					lowerCAmelCase__					:			int=0						):





					"""simple docstring"""






					if is_accelerate_available():
							from accelerate import cpu_offload
					else:
							raise ImportError("""Please install accelerate via `pip install accelerate`"""						)

					__SCREAMING_SNAKE_CASE	:		List[str]   	=		torch.device(F"cuda:{gpu_id}"						)

					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		[self.text_encoder, self.prior]
					for cpu_offloaded_model in models:
							if cpu_offloaded_model is not None:
									cpu_offload(lowerCAmelCase__							,					lowerCAmelCase__						)

			def UpperCamelCase__ (							self					:			int							,					lowerCAmelCase__					:			str=0						):





					"""simple docstring"""






					if is_accelerate_available() and is_accelerate_version(""">="""							,					"""0.17.0.dev0"""						):
							from accelerate import cpu_offload_with_hook
					else:
							raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher."""						)

					__SCREAMING_SNAKE_CASE	:		List[str]   	=		torch.device(F"cuda:{gpu_id}"						)

					if self.device.type != "cpu":
							self.to("""cpu"""							,					silence_dtype_warnings=lowerCAmelCase__						)
							torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

					__SCREAMING_SNAKE_CASE	:		List[str]   	=		None
					for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
							__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	:		Dict   	=		cpu_offload_with_hook(lowerCAmelCase__							,					lowerCAmelCase__							,					prev_module_hook=lowerCAmelCase__						)

					if self.safety_checker is not None:
							__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	:		List[str]   	=		cpu_offload_with_hook(self.safety_checker							,					lowerCAmelCase__							,					prev_module_hook=lowerCAmelCase__						)

					# We'll offload the last model manually.
					__SCREAMING_SNAKE_CASE	:		str   	=		hook

			@property
			def UpperCamelCase__ (							self					:			List[str]						):





					"""simple docstring"""






					if self.device != torch.device("""meta"""						) or not hasattr(self.text_encoder							,					"""_hf_hook"""						):
							return self.device
					for module in self.text_encoder.modules():
							if (
							    hasattr(lowerCAmelCase__							,					"""_hf_hook"""						)
							    and hasattr(module._hf_hook							,					"""execution_device"""						)
							    and module._hf_hook.execution_device is not None
							):
									return torch.device(module._hf_hook.execution_device						)
					return self.device

			def UpperCamelCase__ (							self					:			Optional[int]							,					lowerCAmelCase__					:			Any							,					lowerCAmelCase__					:			Any							,					lowerCAmelCase__					:			Any							,					lowerCAmelCase__					:			Tuple							,					):





					"""simple docstring"""






					len(lowerCAmelCase__						) if isinstance(lowerCAmelCase__							,					lowerCAmelCase__						) else 1

					# YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
					__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		0
					# get prompt text embeddings
					__SCREAMING_SNAKE_CASE	:		Tuple   	=		self.tokenizer(
					    lowerCAmelCase__							,					padding="""max_length"""							,					max_length=self.tokenizer.model_max_length							,					truncation=lowerCAmelCase__							,					return_tensors="""pt"""							,					)
					__SCREAMING_SNAKE_CASE	:		str   	=		text_inputs.input_ids
					__SCREAMING_SNAKE_CASE	:		Dict   	=		self.tokenizer(lowerCAmelCase__							,					padding="""longest"""							,					return_tensors="""pt"""						).input_ids

					if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(lowerCAmelCase__							,					lowerCAmelCase__						):
							__SCREAMING_SNAKE_CASE	:		Dict   	=		self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]						)
							logger.warning(
							    """The following part of your input was truncated because CLIP can only handle sequences up to"""
							    F" {self.tokenizer.model_max_length} tokens: {removed_text}"						)

					__SCREAMING_SNAKE_CASE	:		Any   	=		self.text_encoder(text_input_ids.to(lowerCAmelCase__						)						)
					__SCREAMING_SNAKE_CASE	:		Any   	=		text_encoder_output.text_embeds

					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		prompt_embeds.repeat_interleave(lowerCAmelCase__							,					dim=0						)
					# in Shap-E it normalize the prompt_embeds and then later rescale it
					__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		prompt_embeds / torch.linalg.norm(lowerCAmelCase__							,					dim=-1							,					keepdim=lowerCAmelCase__						)

					if do_classifier_free_guidance:
							__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		torch.zeros_like(lowerCAmelCase__						)

							# For classifier free guidance, we need to do two forward passes.
							# Here we concatenate the unconditional and text embeddings into a single batch
							# to avoid doing two forward passes
							__SCREAMING_SNAKE_CASE	:		List[str]   	=		torch.cat([negative_prompt_embeds, prompt_embeds]						)

					# Rescale the features to have unit variance
					__SCREAMING_SNAKE_CASE	:		Tuple   	=		math.sqrt(prompt_embeds.shape[1]						) * prompt_embeds

					return prompt_embeds



			@torch.no_grad()
			@replace_example_docstring(lowerCAmelCase__						)
			def __call__(							self					:			Union[str, Any]							,					lowerCAmelCase__					:			str							,					lowerCAmelCase__					:			int = 1							,					lowerCAmelCase__					:			int = 2_5							,					lowerCAmelCase__					:			Optional[Union[torch.Generator, List[torch.Generator]]] = None							,					lowerCAmelCase__					:			Optional[torch.FloatTensor] = None							,					lowerCAmelCase__					:			float = 4.0							,					lowerCAmelCase__					:			int = 6_4							,					lowerCAmelCase__					:			Optional[str] = "pil"							,					lowerCAmelCase__					:			bool = True							,					):





					"""simple docstring"""






					if isinstance(lowerCAmelCase__							,					lowerCAmelCase__						):
							__SCREAMING_SNAKE_CASE	:		str   	=		1
					elif isinstance(lowerCAmelCase__							,					lowerCAmelCase__						):
							__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		len(lowerCAmelCase__						)
					else:
							raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(lowerCAmelCase__						)}"						)

					__SCREAMING_SNAKE_CASE	:		Dict   	=		self._execution_device

					__SCREAMING_SNAKE_CASE	:		str   	=		batch_size * num_images_per_prompt

					__SCREAMING_SNAKE_CASE	:		str   	=		guidance_scale > 1.0
					__SCREAMING_SNAKE_CASE	:		int   	=		self._encode_prompt(lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__						)

					# prior

					self.scheduler.set_timesteps(lowerCAmelCase__							,					device=lowerCAmelCase__						)
					__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		self.scheduler.timesteps

					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		self.prior.config.num_embeddings
					__SCREAMING_SNAKE_CASE	:		int   	=		self.prior.config.embedding_dim

					__SCREAMING_SNAKE_CASE	:		str   	=		self.prepare_latents(
					    (batch_size, num_embeddings * embedding_dim)							,					prompt_embeds.dtype							,					lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__							,					self.scheduler							,					)

					# YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		latents.reshape(latents.shape[0]							,					lowerCAmelCase__							,					lowerCAmelCase__						)

					for i, t in enumerate(self.progress_bar(lowerCAmelCase__						)						):
							# expand the latents if we are doing classifier free guidance
							__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		torch.cat([latents] * 2						) if do_classifier_free_guidance else latents
							__SCREAMING_SNAKE_CASE	:		str   	=		self.scheduler.scale_model_input(lowerCAmelCase__							,					lowerCAmelCase__						)

							__SCREAMING_SNAKE_CASE	:		str   	=		self.prior(
							    lowerCAmelCase__							,					timestep=lowerCAmelCase__							,					proj_embedding=lowerCAmelCase__							,					).predicted_image_embedding

							# remove the variance
							__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	:		List[Any]   	=		noise_pred.split(
							    scaled_model_input.shape[2]							,					dim=2						)  # batch_size, num_embeddings, embedding_dim

							if do_classifier_free_guidance is not None:
									__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	:		Any   	=		noise_pred.chunk(2						)
									__SCREAMING_SNAKE_CASE	:		str   	=		noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

							__SCREAMING_SNAKE_CASE	:		str   	=		self.scheduler.step(
							    lowerCAmelCase__							,					timestep=lowerCAmelCase__							,					sample=lowerCAmelCase__							,					).prev_sample

					if output_type == "latent":
							return ShapEPipelineOutput(images=lowerCAmelCase__						)

					__SCREAMING_SNAKE_CASE	:		Dict   	=		[]
					for i, latent in enumerate(lowerCAmelCase__						):
							__SCREAMING_SNAKE_CASE	:		List[Any]   	=		self.renderer.decode(
							    latent[None, :]							,					lowerCAmelCase__							,					size=lowerCAmelCase__							,					ray_batch_size=4_0_9_6							,					n_coarse_samples=6_4							,					n_fine_samples=1_2_8							,					)
							images.append(lowerCAmelCase__						)

					__SCREAMING_SNAKE_CASE	:		Dict   	=		torch.stack(lowerCAmelCase__						)

					if output_type not in ["np", "pil"]:
							raise ValueError(F"Only the output types `pil` and `np` are supported not output_type={output_type}"						)

					__SCREAMING_SNAKE_CASE	:		str   	=		images.cpu().numpy()

					if output_type == "pil":
							__SCREAMING_SNAKE_CASE	:		int   	=		[self.numpy_to_pil(lowerCAmelCase__						) for image in images]

					# Offload last model to CPU
					if hasattr(self							,					"""final_offload_hook"""						) and self.final_offload_hook is not None:
							self.final_offload_hook.offload()

					if not return_dict:
							return (images,)

					return ShapEPipelineOutput(images=lowerCAmelCase__						)