import json
import os
import shutil
import sys
import tempfile
import unittest
from unittest import TestCase
from unittest.mock import patch

import faiss
import numpy as np
from datasets import Dataset

from transformers import BartConfig, BartTokenizer, DPRConfig, DPRQuestionEncoderTokenizer, RagConfig
from transformers.file_utils import is_datasets_available, is_faiss_available, is_psutil_available, is_torch_available
from transformers.integrations import is_ray_available
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
from transformers.testing_utils import require_ray


sys.path.append(os.path.join(os.getcwd()))  # noqa: E402 # noqa: E402 # isort:skip

if is_torch_available():
    from distributed_pytorch_retriever import RagPyTorchDistributedRetriever  # noqa: E402 # isort:skip
else:
    lowerCAmelCase__							= None

if is_ray_available():
    import ray  # noqa: E402 # isort:skip
    from distributed_ray_retriever import RagRayDistributedRetriever, RayRetriever  # noqa: E402 # isort:skip
else:
    lowerCAmelCase__							= None
    lowerCAmelCase__							= None
    lowerCAmelCase__							= None






def       __lowerCamelCase		(						lowerCAmelCase__	):

       if not (is_datasets_available() and is_faiss_available() and is_psutil_available()):
              lowerCAmelCase__     	=					unittest.skip('test requires Datasets, Faiss, psutil'	)(a__	)
       return test_case



@require_distributed_retrieval
class 				a_ (						SCREAMING_SNAKE_CASE						):






 '''simple docstring'''






 def 		__snake_case						(			self					:  str):







        '''simple docstring'''



        lowerCAmelCase__     	=					tempfile.mkdtemp()
        lowerCAmelCase__     	=					8

        # DPR tok
        lowerCAmelCase__     	=					[
            '[UNK]',
            '[CLS]',
            '[SEP]',
            '[PAD]',
            '[MASK]',
            'want',
            '##want',
            '##ed',
            'wa',
            'un',
            'runn',
            '##ing',
            ',',
            'low',
            'lowest',
        ]
        lowerCAmelCase__     	=					os.path.join(self.tmpdirname			,    'dpr_tokenizer')
        os.makedirs(lowercase_			,    exist_ok=lowercase_)
        lowerCAmelCase__     	=					os.path.join(lowercase_			,    DPR_VOCAB_FILES_NAMES['vocab_file'])
        with open(self.vocab_file			,    'w'			,    encoding='utf-8') as vocab_writer:
               vocab_writer.write(''.join([x + '\n' for x in vocab_tokens]))

        # BART tok
        lowerCAmelCase__     	=					[
            'l',
            'o',
            'w',
            'e',
            'r',
            's',
            't',
            'i',
            'd',
            'n',
            '\u0120',
            '\u0120l',
            '\u0120n',
            '\u0120lo',
            '\u0120low',
            'er',
            '\u0120lowest',
            '\u0120newer',
            '\u0120wider',
            '<unk>',
        ]
        lowerCAmelCase__     	=					dict(zip(lowercase_			,    range(len(lowercase_))))
        lowerCAmelCase__     	=					['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', '']
        lowerCAmelCase__     	=					{'unk_token': '<unk>'}

        lowerCAmelCase__     	=					os.path.join(self.tmpdirname			,    'bart_tokenizer')
        os.makedirs(lowercase_			,    exist_ok=lowercase_)
        lowerCAmelCase__     	=					os.path.join(lowercase_			,    BART_VOCAB_FILES_NAMES['vocab_file'])
        lowerCAmelCase__     	=					os.path.join(lowercase_			,    BART_VOCAB_FILES_NAMES['merges_file'])
        with open(self.vocab_file			,    'w'			,    encoding='utf-8') as fp:
               fp.write(json.dumps(lowercase_) + '\n')
        with open(self.merges_file			,    'w'			,    encoding='utf-8') as fp:
               fp.write('\n'.join(lowercase_))




 def 		__snake_case						(			self					:  Optional[int]):







        '''simple docstring'''



        return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname			,    'dpr_tokenizer'))




 def 		__snake_case						(			self					:  List[Any]):







        '''simple docstring'''



        return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname			,    'bart_tokenizer'))




 def 		__snake_case						(			self					:  List[Any]):







        '''simple docstring'''



        shutil.rmtree(self.tmpdirname)




 def 		__snake_case						(			self					:  Dict):







        '''simple docstring'''



        lowerCAmelCase__     	=					Dataset.from_dict(
            {
                'id': ['0', '1'],
                'text': ['foo', 'bar'],
                'title': ['Foo', 'Bar'],
                'embeddings': [np.ones(self.retrieval_vector_size), 2 * np.ones(self.retrieval_vector_size)],
            })
        dataset.add_faiss_index('embeddings'			,    string_factory='Flat'			,    metric_type=faiss.METRIC_INNER_PRODUCT)
        return dataset




 def 		__snake_case						(			self					:  List[Any]			,    lowercase__					:  bool			,    lowercase__					:  Tuple=12_345):







        '''simple docstring'''



        lowerCAmelCase__     	=					self.get_dummy_dataset()
        lowerCAmelCase__     	=					RagConfig(
            retrieval_vector_size=self.retrieval_vector_size			,    question_encoder=DPRConfig().to_dict()			,    generator=BartConfig().to_dict()			,    )
        with patch('transformers.models.rag.retrieval_rag.load_dataset') as mock_load_dataset:
               lowerCAmelCase__     	=					dataset
               lowerCAmelCase__     	=					RagPyTorchDistributedRetriever(
                   lowercase_			,    question_encoder_tokenizer=self.get_dpr_tokenizer()			,    generator_tokenizer=self.get_bart_tokenizer()			,    )
               if init_retrieval:
                      retriever.init_retrieval(lowercase_)
        return retriever




 def 		__snake_case						(			self					:  Any			,    lowercase__					:  bool):







        '''simple docstring'''



        ray.init(local_mode=lowercase_)
        lowerCAmelCase__     	=					RagConfig(
            retrieval_vector_size=self.retrieval_vector_size			,    question_encoder=DPRConfig().to_dict()			,    generator=BartConfig().to_dict()			,    )
        lowerCAmelCase__     	=					ray.remote(lowercase_)
        lowerCAmelCase__     	=					[remote_cls.remote() for _ in range(1)]
        with patch('transformers.models.rag.retrieval_rag.load_dataset') as mock_load_dataset:
               lowerCAmelCase__     	=					self.get_dummy_dataset()
               lowerCAmelCase__     	=					RagRayDistributedRetriever(
                   lowercase_			,    question_encoder_tokenizer=self.get_dpr_tokenizer()			,    generator_tokenizer=self.get_bart_tokenizer()			,    retrieval_workers=lowercase_			,    )
               if init_retrieval:
                      retriever.init_retrieval()
        return retriever




 def 		__snake_case						(			self					:  Union[str, Any]			,    lowercase__					:  bool			,    lowercase__					:  bool			,    lowercase__					:  List[Any]=12_345):







        '''simple docstring'''



        lowerCAmelCase__     	=					self.get_dummy_dataset()
        lowerCAmelCase__     	=					RagConfig(
            retrieval_vector_size=self.retrieval_vector_size			,    question_encoder=DPRConfig().to_dict()			,    generator=BartConfig().to_dict()			,    index_name='custom'			,    )
        if from_disk:
               lowerCAmelCase__     	=					os.path.join(self.tmpdirname			,    'dataset')
               lowerCAmelCase__     	=					os.path.join(self.tmpdirname			,    'index.faiss')
               dataset.get_index('embeddings').save(os.path.join(self.tmpdirname			,    'index.faiss'))
               dataset.drop_index('embeddings')
               dataset.save_to_disk(os.path.join(self.tmpdirname			,    'dataset'))
               del dataset
               lowerCAmelCase__     	=					RagPyTorchDistributedRetriever(
                   lowercase_			,    question_encoder_tokenizer=self.get_dpr_tokenizer()			,    generator_tokenizer=self.get_bart_tokenizer()			,    )
        else:
               lowerCAmelCase__     	=					RagPyTorchDistributedRetriever(
                   lowercase_			,    question_encoder_tokenizer=self.get_dpr_tokenizer()			,    generator_tokenizer=self.get_bart_tokenizer()			,    index=CustomHFIndex(config.retrieval_vector_size			,    lowercase_)			,    )
        if init_retrieval:
               retriever.init_retrieval(lowercase_)
        return retriever




 def 		__snake_case						(			self					:  Optional[Any]			,    lowercase__					:  bool			,    lowercase__					:  bool):







        '''simple docstring'''



        ray.init(local_mode=lowercase_)
        lowerCAmelCase__     	=					self.get_dummy_dataset()
        lowerCAmelCase__     	=					RagConfig(
            retrieval_vector_size=self.retrieval_vector_size			,    question_encoder=DPRConfig().to_dict()			,    generator=BartConfig().to_dict()			,    index_name='custom'			,    )
        lowerCAmelCase__     	=					ray.remote(lowercase_)
        lowerCAmelCase__     	=					[remote_cls.remote() for _ in range(1)]
        if from_disk:
               lowerCAmelCase__     	=					os.path.join(self.tmpdirname			,    'dataset')
               lowerCAmelCase__     	=					os.path.join(self.tmpdirname			,    'index.faiss')
               dataset.get_index('embeddings').save(os.path.join(self.tmpdirname			,    'index.faiss'))
               dataset.drop_index('embeddings')
               dataset.save_to_disk(os.path.join(self.tmpdirname			,    'dataset'))
               del dataset
               lowerCAmelCase__     	=					RagRayDistributedRetriever(
                   lowercase_			,    question_encoder_tokenizer=self.get_dpr_tokenizer()			,    generator_tokenizer=self.get_bart_tokenizer()			,    retrieval_workers=lowercase_			,    index=CustomHFIndex.load_from_disk(
                       vector_size=config.retrieval_vector_size			,    dataset_path=config.passages_path			,    index_path=config.index_path			,    )			,    )
        else:
               lowerCAmelCase__     	=					RagRayDistributedRetriever(
                   lowercase_			,    question_encoder_tokenizer=self.get_dpr_tokenizer()			,    generator_tokenizer=self.get_bart_tokenizer()			,    retrieval_workers=lowercase_			,    index=CustomHFIndex(config.retrieval_vector_size			,    lowercase_)			,    )
        if init_retrieval:
               retriever.init_retrieval()
        return retriever




 def 		__snake_case						(			self					:  str			,    lowercase__					:  RagRetriever			,    lowercase__					:  np.array			,    lowercase__					:  int):







        '''simple docstring'''



        lowerCAmelCase__	,					lowerCAmelCase__	,					lowerCAmelCase__     	=					retriever.retrieve(lowercase_			,    n_docs=lowercase_)
        self.assertEqual(retrieved_doc_embeds.shape			,    (2, n_docs, self.retrieval_vector_size))
        self.assertEqual(len(lowercase_)			,    2)
        self.assertEqual(sorted(doc_dicts[0])			,    ['embeddings', 'id', 'text', 'title'])
        self.assertEqual(len(doc_dicts[0]['id'])			,    lowercase_)
        self.assertEqual(doc_dicts[0]['id'][0]			,    '1')  # max inner product is reached with second doc
        self.assertEqual(doc_dicts[1]['id'][0]			,    '0')  # max inner product is reached with first doc
        self.assertListEqual(doc_ids.tolist()			,    [[1], [0]])




 def 		__snake_case						(			self					:  Tuple):







        '''simple docstring'''



        lowerCAmelCase__     	=					1
        lowerCAmelCase__     	=					np.array(
            [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)]			,    dtype=np.floataa)

        self.distributed_retriever_check(
            self.get_dummy_pytorch_distributed_retriever(init_retrieval=lowercase_)			,    lowercase_			,    lowercase_)




 def 		__snake_case						(			self					:  List[str]):







        '''simple docstring'''



        lowerCAmelCase__     	=					1
        lowerCAmelCase__     	=					np.array(
            [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)]			,    dtype=np.floataa)

        self.distributed_retriever_check(
            self.get_dummy_custom_hf_index_pytorch_retriever(init_retrieval=lowercase_			,    from_disk=lowercase_)			,    lowercase_			,    lowercase_			,    )




 def 		__snake_case						(			self					:  Dict):







        '''simple docstring'''



        lowerCAmelCase__     	=					1
        lowerCAmelCase__     	=					np.array(
            [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)]			,    dtype=np.floataa)

        self.distributed_retriever_check(
            self.get_dummy_custom_hf_index_pytorch_retriever(init_retrieval=lowercase_			,    from_disk=lowercase_)			,    lowercase_			,    lowercase_			,    )




 @require_ray
 def 		__snake_case						(			self					:  Optional[int]):







        '''simple docstring'''



        lowerCAmelCase__     	=					1
        lowerCAmelCase__     	=					np.array(
            [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)]			,    dtype=np.floataa)

        self.distributed_retriever_check(
            self.get_dummy_ray_distributed_retriever(init_retrieval=lowercase_)			,    lowercase_			,    lowercase_)
        ray.shutdown()




 @require_ray
 def 		__snake_case						(			self					:  Any):







        '''simple docstring'''



        lowerCAmelCase__     	=					1
        lowerCAmelCase__     	=					np.array(
            [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)]			,    dtype=np.floataa)
        with self.assertRaises(lowercase_):
               self.distributed_retriever_check(
                   self.get_dummy_custom_hf_index_ray_retriever(init_retrieval=lowercase_			,    from_disk=lowercase_)			,    lowercase_			,    lowercase_			,    )
        ray.shutdown()




 @require_ray
 def 		__snake_case						(			self					:  int):







        '''simple docstring'''



        lowerCAmelCase__     	=					1
        lowerCAmelCase__     	=					np.array(
            [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)]			,    dtype=np.floataa)

        self.distributed_retriever_check(
            self.get_dummy_custom_hf_index_ray_retriever(init_retrieval=lowercase_			,    from_disk=lowercase_)			,    lowercase_			,    lowercase_)
        ray.shutdown()

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							:					Tuple				,      lowercase_							:					int				,      lowercase_							:					Union[str, Any]=13				,      lowercase_							:					Optional[int]=7				,      lowercase_							:					Optional[Any]=True				,      lowercase_							:					Tuple=True				,      lowercase_							:					str=True				,      lowercase_							:					Union[str, Any]=True				,      lowercase_							:					int=99				,      lowercase_							:					Dict=32				,      lowercase_							:					Optional[int]=5				,      lowercase_							:					List[Any]=4				,      lowercase_							:					List[str]=37				,      lowercase_							:					Dict="gelu"				,      lowercase_							:					Union[str, Any]=0.1				,      lowercase_							:					List[Any]=0.1				,      lowercase_							:					int=512				,      lowercase_							:					int=16				,      lowercase_							:					Dict=2				,      lowercase_							:					Union[str, Any]=0.02				,      lowercase_							:					List[Any]=3				,      lowercase_							:					List[Any]=4				,      lowercase_							:					Optional[Any]=None				,      lowercase_							:					List[Any]=1000				,      )		->     Optional[int]:


   """simple docstring"""







   _UpperCamelCase				=  parent
   _UpperCamelCase				=  batch_size
   _UpperCamelCase				=  seq_length
   _UpperCamelCase				=  is_training
   _UpperCamelCase				=  use_input_mask
   _UpperCamelCase				=  use_token_type_ids
   _UpperCamelCase				=  use_labels
   _UpperCamelCase				=  vocab_size
   _UpperCamelCase				=  hidden_size
   _UpperCamelCase				=  num_hidden_layers
   _UpperCamelCase				=  num_attention_heads
   _UpperCamelCase				=  intermediate_size
   _UpperCamelCase				=  hidden_act
   _UpperCamelCase				=  hidden_dropout_prob
   _UpperCamelCase				=  attention_probs_dropout_prob
   _UpperCamelCase				=  max_position_embeddings
   _UpperCamelCase				=  type_vocab_size
   _UpperCamelCase				=  type_sequence_label_size
   _UpperCamelCase				=  initializer_range
   _UpperCamelCase				=  num_labels
   _UpperCamelCase				=  num_choices
   _UpperCamelCase				=  scope
   _UpperCamelCase				=  range_bbox







 def 						__UpperCAmelCase							(						self							:					Union[str, Any])		->     Optional[Any]:


   """simple docstring"""







   _UpperCamelCase				=  ids_tensor([self.batch_size, self.seq_length]				,      self.vocab_size)

   _UpperCamelCase				=  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]:
         _UpperCamelCase				=  bbox[i, j, 3]
         _UpperCamelCase				=  bbox[i, j, 1]
         _UpperCamelCase				=  t
       if bbox[i, j, 2] < bbox[i, j, 0]:
         _UpperCamelCase				=  bbox[i, j, 2]
         _UpperCamelCase				=  bbox[i, j, 0]
         _UpperCamelCase				=  t

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

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

   _UpperCamelCase				=  None
   _UpperCamelCase				=  None
   _UpperCamelCase				=  None
   if self.use_labels:
     _UpperCamelCase				=  ids_tensor([self.batch_size]				,      self.type_sequence_label_size)
     _UpperCamelCase				=  ids_tensor([self.batch_size, self.seq_length]				,      self.num_labels)
     _UpperCamelCase				=  ids_tensor([self.batch_size]				,      self.num_choices)

   _UpperCamelCase				=  self.get_config()

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







 def 						__UpperCAmelCase							(						self							:					Union[str, Any])		->     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							:					List[str]				,      lowercase_							:					Optional[Any]				,      lowercase_							:					str				,      lowercase_							:					Optional[Any]				,      lowercase_							:					Any				,      lowercase_							:					Dict				,      lowercase_							:					List[str]				,      lowercase_							:					Dict				,      lowercase_							:					List[str])		->     List[Any]:


   """simple docstring"""







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


   """simple docstring"""







   _UpperCamelCase				=  LayoutLMForMaskedLM(config=lowercase_)
   model.to(lowercase_)
   model.eval()
   _UpperCamelCase				=  model(lowercase_				,      lowercase_				,      attention_mask=lowercase_				,      token_type_ids=lowercase_				,      labels=lowercase_)
   self.parent.assertEqual(result.logits.shape				,      (self.batch_size, self.seq_length, self.vocab_size))







 def 						__UpperCAmelCase							(						self							:					Union[str, Any]				,      lowercase_							:					List[Any]				,      lowercase_							:					Optional[int]				,      lowercase_							:					Union[str, Any]				,      lowercase_							:					Optional[int]				,      lowercase_							:					Dict				,      lowercase_							:					int				,      lowercase_							:					Dict				,      lowercase_							:					List[str])		->     Any:


   """simple docstring"""







   _UpperCamelCase				=  self.num_labels
   _UpperCamelCase				=  LayoutLMForSequenceClassification(lowercase_)
   model.to(lowercase_)
   model.eval()
   _UpperCamelCase				=  model(
       lowercase_				,      lowercase_				,      attention_mask=lowercase_				,      token_type_ids=lowercase_				,      labels=lowercase_)
   self.parent.assertEqual(result.logits.shape				,      (self.batch_size, self.num_labels))







 def 						__UpperCAmelCase							(						self							:					List[Any]				,      lowercase_							:					Optional[Any]				,      lowercase_							:					Optional[Any]				,      lowercase_							:					Optional[Any]				,      lowercase_							:					Dict				,      lowercase_							:					Dict				,      lowercase_							:					Union[str, Any]				,      lowercase_							:					str				,      lowercase_							:					Tuple)		->     List[Any]:


   """simple docstring"""







   _UpperCamelCase				=  self.num_labels
   _UpperCamelCase				=  LayoutLMForTokenClassification(config=lowercase_)
   model.to(lowercase_)
   model.eval()
   _UpperCamelCase				=  model(lowercase_				,      lowercase_				,      attention_mask=lowercase_				,      token_type_ids=lowercase_				,      labels=lowercase_)
   self.parent.assertEqual(result.logits.shape				,      (self.batch_size, self.seq_length, self.num_labels))







 def 						__UpperCAmelCase							(						self							:					str				,      lowercase_							:					Optional[Any]				,      lowercase_							:					Tuple				,      lowercase_							:					Optional[Any]				,      lowercase_							:					Optional[Any]				,      lowercase_							:					Tuple				,      lowercase_							:					str				,      lowercase_							:					Optional[Any]				,      lowercase_							:					Optional[Any])		->     Tuple:


   """simple docstring"""







   _UpperCamelCase				=  LayoutLMForQuestionAnswering(config=lowercase_)
   model.to(lowercase_)
   model.eval()
   _UpperCamelCase				=  model(
       lowercase_				,      bbox=lowercase_				,      attention_mask=lowercase_				,      token_type_ids=lowercase_				,      start_positions=lowercase_				,      end_positions=lowercase_				,      )
   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							:					Dict)		->     List[str]:


   """simple docstring"""







   _UpperCamelCase				=  self.prepare_config_and_inputs()
   (
       (
       _UpperCamelCase
   )	,		(
       _UpperCamelCase
   )	,		(
       _UpperCamelCase
   )	,		(
       _UpperCamelCase
   )	,		(
       _UpperCamelCase
   )	,		(
       _UpperCamelCase
   )	,		(
       _UpperCamelCase
   )	,		(
       _UpperCamelCase
   )	,		
   )				=  config_and_inputs
   _UpperCamelCase				=  {
       "input_ids": input_ids,
       "bbox": bbox,
       "token_type_ids": token_type_ids,
       "attention_mask": input_mask,
   }
   return config, inputs_dict




@require_torch
class  _UpperCAmelCase       (			lowerCAmelCase,       lowerCAmelCase,       unittest.TestCase   ):



 '''simple docstring'''




 __A           = (
     (
         LayoutLMModel,
         LayoutLMForMaskedLM,
         LayoutLMForSequenceClassification,
         LayoutLMForTokenClassification,
         LayoutLMForQuestionAnswering,
     )
     if is_torch_available()
     else None
 )
 __A           = (
     {
         '''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           = True







 def 						__UpperCAmelCase							(						self							:					List[Any])		->     List[str]:


   """simple docstring"""







   _UpperCamelCase				=  LayoutLMModelTester(self)
   _UpperCamelCase				=  ConfigTester(self				,      config_class=lowercase_				,      hidden_size=37)







 def 						__UpperCAmelCase							(						self							:					List[Any])		->     Union[str, Any]:


   """simple docstring"""







   self.config_tester.run_common_tests()







 def 						__UpperCAmelCase							(						self							:					Optional[int])		->     str:


   """simple docstring"""







   _UpperCamelCase				=  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*lowercase_)







 def 						__UpperCAmelCase							(						self							:					List[Any])		->     Dict:


   """simple docstring"""







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







 def 						__UpperCAmelCase							(						self							:					Any)		->     Optional[Any]:


   """simple docstring"""







   _UpperCamelCase				=  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_masked_lm(*lowercase_)







 def 						__UpperCAmelCase							(						self							:					Dict)		->     str:


   """simple docstring"""







   _UpperCamelCase				=  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_sequence_classification(*lowercase_)







 def 						__UpperCAmelCase							(						self							:					Tuple)		->     Dict:


   """simple docstring"""







   _UpperCamelCase				=  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_token_classification(*lowercase_)







 def 						__UpperCAmelCase							(						self							:					List[str])		->     Optional[int]:


   """simple docstring"""







   _UpperCamelCase				=  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_question_answering(*lowercase_)







 @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests.")
 def 						__UpperCAmelCase							(						self							:					Tuple)		->     List[str]:


   """simple docstring"""







   pass


def 							lowerCAmelCase__    (       )	->Union[str, Any]:




  '''simple docstring'''

  _UpperCamelCase				=  torch.tensor([[101,1_019,1_014,1_016,1_037,12_849,4_747,1_004,14_246,2_278,5_439,4_524,5_002,2_930,2_193,2_930,4_341,3_208,1_005,1_055,2_171,2_848,11_300,3_531,102],[101,4_070,4_034,7_020,1_024,3_058,1_015,1_013,2_861,1_013,6_070,19_274,2_772,6_205,27_814,16_147,16_147,4_343,2_047,10_283,10_969,14_389,1_012,2_338,102]]  ,			device=a__      )  # noqa: E231
  _UpperCamelCase				=  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
  _UpperCamelCase				=  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],[1_000,1_000,1_000,1_000]],[[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],[1_000,1_000,1_000,1_000]]]  ,			device=a__      )  # noqa: E231
  _UpperCamelCase				=  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)
  _UpperCamelCase				=  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  _UpperCAmelCase       (			unittest.TestCase   ):



 '''simple docstring'''




 @slow
 def 						__UpperCAmelCase							(						self							:					Any)		->     Union[str, Any]:


   """simple docstring"""







   _UpperCamelCase				=  LayoutLMModel.from_pretrained("microsoft/layoutlm-base-uncased").to(lowercase_)

   _UpperCamelCase	,		_UpperCamelCase	,		_UpperCamelCase	,		_UpperCamelCase	,		_UpperCamelCase				=  prepare_layoutlm_batch_inputs()

   # forward pass
   _UpperCamelCase				=  model(input_ids=lowercase_				,      bbox=lowercase_				,      attention_mask=lowercase_				,      token_type_ids=lowercase_)

   # test the sequence output on [0, :3, :3]
   _UpperCamelCase				=  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=lowercase_				,      )

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

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

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







 @slow
 def 						__UpperCAmelCase							(						self							:					Optional[int])		->     List[str]:


   """simple docstring"""







   _UpperCamelCase				=  LayoutLMForSequenceClassification.from_pretrained("microsoft/layoutlm-base-uncased"				,      num_labels=2).to(
       lowercase_)

   _UpperCamelCase	,		_UpperCamelCase	,		_UpperCamelCase	,		_UpperCamelCase	,		_UpperCamelCase				=  prepare_layoutlm_batch_inputs()

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

   # test whether we get a loss as a scalar
   _UpperCamelCase				=  outputs.loss
   _UpperCamelCase				=  torch.Size([])
   self.assertEqual(loss.shape				,      lowercase_)

   # test the shape of the logits
   _UpperCamelCase				=  outputs.logits
   _UpperCamelCase				=  torch.Size((2, 2))
   self.assertEqual(logits.shape				,      lowercase_)







 @slow
 def 						__UpperCAmelCase							(						self							:					Tuple)		->     Any:


   """simple docstring"""







   _UpperCamelCase				=  LayoutLMForTokenClassification.from_pretrained("microsoft/layoutlm-base-uncased"				,      num_labels=13).to(
       lowercase_)

   _UpperCamelCase	,		_UpperCamelCase	,		_UpperCamelCase	,		_UpperCamelCase	,		_UpperCamelCase				=  prepare_layoutlm_batch_inputs()

   # forward pass
   _UpperCamelCase				=  model(
       input_ids=lowercase_				,      bbox=lowercase_				,      attention_mask=lowercase_				,      token_type_ids=lowercase_				,      labels=lowercase_)

   # 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
   _UpperCamelCase				=  outputs.logits
   _UpperCamelCase				=  torch.Size((2, 25, 13))
   self.assertEqual(logits.shape				,      lowercase_)







 @slow
 def 						__UpperCAmelCase							(						self							:					Any)		->     int:


   """simple docstring"""







   _UpperCamelCase				=  LayoutLMForQuestionAnswering.from_pretrained("microsoft/layoutlm-base-uncased").to(lowercase_)

   _UpperCamelCase	,		_UpperCamelCase	,		_UpperCamelCase	,		_UpperCamelCase	,		_UpperCamelCase				=  prepare_layoutlm_batch_inputs()

   # forward pass
   _UpperCamelCase				=  model(input_ids=lowercase_				,      bbox=lowercase_				,      attention_mask=lowercase_				,      token_type_ids=lowercase_)

   # test the shape of the logits
   _UpperCamelCase				=  torch.Size((2, 25))
   self.assertEqual(outputs.start_logits.shape				,      lowercase_)
   self.assertEqual(outputs.end_logits.shape				,      lowercase_)




