
"""simple docstring"""




import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
_A			:       str   		=       pytest.mark.integration


_A			:       str   		=       {"""comet"""}
_A			:       str   		=       importlib.util.find_spec("""fairseq""") is not None

_A			:       Optional[Any]   		=       {"""code_eval"""}
_A			:       List[str]   		=       os.name == """nt"""

_A			:       Union[str, Any]   		=       {"""bertscore""", """frugalscore""", """perplexity"""}
_A			:       List[Any]   		=       importlib.util.find_spec("""transformers""") is not None


def   __magic_name__	(      __snake_case				:       Union[str, Any]  ) ->				Optional[int]:
       @wraps(__snake_case  )
       def wrapper(self				:       str     , __snake_case				:       Tuple  ):
              if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
                     self.skipTest("\"test requires Fairseq\""  )
              else:
                     test_case(self     , __snake_case  )

       return wrapper


def   __magic_name__	(      __snake_case				:       int  ) ->				str:
       @wraps(__snake_case  )
       def wrapper(self				:       Any     , __snake_case				:       Optional[Any]  ):
              if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
                     self.skipTest("\"test requires transformers\""  )
              else:
                     test_case(self     , __snake_case  )

       return wrapper


def   __magic_name__	(      __snake_case				:       Tuple  ) ->				Union[str, Any]:
       @wraps(__snake_case  )
       def wrapper(self				:       Tuple     , __snake_case				:       List[Any]  ):
              if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
                     self.skipTest("\"test not supported on Windows\""  )
              else:
                     test_case(self     , __snake_case  )

       return wrapper


def   __magic_name__	(      ) ->				Dict:
       lowercase    :				Optional[Any]       		=							[metric_dir.split(os.sep  )[-2] for metric_dir in glob.glob("./metrics/*/"  )]
       return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished

@parameterized.named_parameters(get_local_metric_names()						)
@for_all_test_methods(
    a_,			a_,			a_						)
@local
class 		a__						(      parameterized.TestCase						):
   __lowerCAmelCase            =				{}
   __lowerCAmelCase            =				None
   @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning"				)
   @pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning"				)
   def 			__magic_name__			(			self	,    _a				):
          lowercase    :				Any       		=							"[...]"
          lowercase    :				Dict       		=							importlib.import_module(
              datasets.load.metric_module_factory(os.path.join("metrics"	,    _a				)				).module_path				)
          lowercase    :				Union[str, Any]       		=							datasets.load.import_main_class(metric_module.__name__	,    dataset=_a				)
          # check parameters
          lowercase    :				List[str]       		=							inspect.signature(metric._compute				).parameters
          self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()				)				)  # no **kwargs
          # run doctest
          with self.patch_intensive_calls(_a	,    metric_module.__name__				):
                 with self.use_local_metrics():
                        try:
                               lowercase    :				Union[str, Any]       		=							doctest.testmod(_a	,    verbose=_a	,    raise_on_error=_a				)
                        except doctest.UnexpectedException as e:
                               raise e.exc_info[1]  # raise the exception that doctest caught
          self.assertEqual(results.failed	,    0				)
          self.assertGreater(results.attempted	,    1				)
   @slow
   def 			__magic_name__			(			self	,    _a				):
          lowercase    :				Optional[Any]       		=							"[...]"
          lowercase    :				int       		=							importlib.import_module(
              datasets.load.metric_module_factory(os.path.join("metrics"	,    _a				)				).module_path				)
          # run doctest
          with self.use_local_metrics():
                 lowercase    :				Any       		=							doctest.testmod(_a	,    verbose=_a	,    raise_on_error=_a				)
          self.assertEqual(results.failed	,    0				)
          self.assertGreater(results.attempted	,    1				)
   @contextmanager
   def 			__magic_name__			(			self	,    _a	,    _a				):
          if metric_name in self.INTENSIVE_CALLS_PATCHER:
                 with self.INTENSIVE_CALLS_PATCHER[metric_name](_a				):
                        yield
          else:
                 yield
   @contextmanager
   def 			__magic_name__			(			self				):
          def load_local_metric(_a	,    *_a	,    **_a				):
                 return load_metric(os.path.join("metrics"	,    _a				)	,    *_a	,    **_a				)

          with patch("datasets.load_metric"				) as mock_load_metric:
                 lowercase    :				Any       		=							load_local_metric
                 yield

   @classmethod
   def 			__magic_name__			(			cls	,    _a				):
          def wrapper(_a				):
                 lowercase    :				int       		=							contextmanager(_a				)
                 lowercase    :				Optional[int]       		=							patcher
                 return patcher

          return wrapper


@LocalMetricTest.register_intensive_calls_patcher("bleurt"  )
def   __magic_name__	(      __snake_case				:       Dict  ) ->				Tuple:
       import tensorflow.compat.va as tf
       from bleurt.score import Predictor

       tf.flags.DEFINE_string("sv"     , ""     , ""  )  # handle pytest cli flags

       class 		a__						(      a_						):
          def 			__magic_name__			(			self	,    _a				):
                 assert len(input_dict["input_ids"]				) == 2
                 return np.array([1.0_3, 1.0_4]				)

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
       with patch("bleurt.score._create_predictor"  ) as mock_create_predictor:
              lowercase    :				str       		=							MockedPredictor()
              yield


@LocalMetricTest.register_intensive_calls_patcher("bertscore"  )
def   __magic_name__	(      __snake_case				:       Optional[int]  ) ->				Any:
       import torch

       def bert_cos_score_idf(__snake_case				:       Tuple     , __snake_case				:       str     , *__snake_case				:       int     , **__snake_case				:       Union[str, Any]  ):
              return torch.tensor([[1.0, 1.0, 1.0]] * len(__snake_case  )  )

       # mock get_model which is supposed to do download a bert model
       # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
       with patch("bert_score.scorer.get_model"  ), patch(
           "bert_score.scorer.bert_cos_score_idf"  ) as mock_bert_cos_score_idf:
              lowercase    :				Any       		=							bert_cos_score_idf
              yield


@LocalMetricTest.register_intensive_calls_patcher("comet"  )
def   __magic_name__	(      __snake_case				:       Optional[int]  ) ->				Tuple:
       def load_from_checkpoint(__snake_case				:       Any  ):

              class 		a__						:
                 def 			__magic_name__			(			self	,    _a	,    *_a	,    **_a				):
                        assert len(_a				) == 2
                        lowercase    :				str       		=							[0.1_9, 0.9_2]
                        return scores, sum(_a				) / len(_a				)


              return Model()

       # mock load_from_checkpoint which is supposed to do download a bert model
       # mock load_from_checkpoint which is supposed to do download a bert model
       with patch("comet.download_model"  ) as mock_download_model:
              lowercase    :				Optional[Any]       		=							None
              with patch("comet.load_from_checkpoint"  ) as mock_load_from_checkpoint:
                     lowercase    :				int       		=							load_from_checkpoint
                     yield


def   __magic_name__	(      ) ->				Dict:
       lowercase    :				Tuple       		=							load_metric(os.path.join("metrics"     , "seqeval"  )  )
       lowercase    :				Dict       		=							"ERROR"
       lowercase    :				Any       		=							f"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}"""
       with pytest.raises(__snake_case     , match=re.escape(__snake_case  )  ):
              metric.compute(predictions=[]     , references=[]     , scheme=__snake_case  )




"""simple docstring"""




from __future__ import annotations

import unittest

import numpy as np

from transformers import LayoutLMConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
   import tensorflow as tf

   from transformers.models.layoutlm.modeling_tf_layoutlm import (
       TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
       TFLayoutLMForMaskedLM,
       TFLayoutLMForQuestionAnswering,
       TFLayoutLMForSequenceClassification,
       TFLayoutLMForTokenClassification,
       TFLayoutLMModel,
   )

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

          # convert bbox to numpy since TF does not support item assignment
          lowercase    :				int       		=							ids_tensor([self.batch_size, self.seq_length, 4]	,    self.range_bbox				).numpy()
          # 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]:
                               lowercase    :				Any       		=							bbox[i, j, 3]
                               lowercase    :				Optional[Any]       		=							bbox[i, j, 1]
                               lowercase    :				Optional[Any]       		=							t
                        if bbox[i, j, 2] < bbox[i, j, 0]:
                               lowercase    :				Dict       		=							bbox[i, j, 2]
                               lowercase    :				List[str]       		=							bbox[i, j, 0]
                               lowercase    :				List[Any]       		=							t
          lowercase    :				Any       		=							tf.convert_to_tensor(_a				)

          lowercase    :				Dict       		=							None
          if self.use_input_mask:
                 lowercase    :				List[str]       		=							random_attention_mask([self.batch_size, self.seq_length]				)

          lowercase    :				Optional[int]       		=							None
          if self.use_token_type_ids:
                 lowercase    :				Dict       		=							ids_tensor([self.batch_size, self.seq_length]	,    self.type_vocab_size				)

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

          lowercase    :				int       		=							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	,    )

          return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
   def 			__magic_name__			(			self	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a				):
          lowercase    :				str       		=							TFLayoutLMModel(config=_a				)

          lowercase    :				Optional[Any]       		=							model(_a	,    _a	,    attention_mask=_a	,    token_type_ids=_a				)
          lowercase    :				Dict       		=							model(_a	,    _a	,    token_type_ids=_a				)
          lowercase    :				List[str]       		=							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 			__magic_name__			(			self	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a				):
          lowercase    :				List[Any]       		=							TFLayoutLMForMaskedLM(config=_a				)

          lowercase    :				Union[str, 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 			__magic_name__			(			self	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a				):
          lowercase    :				Dict       		=							self.num_labels
          lowercase    :				Any       		=							TFLayoutLMForSequenceClassification(config=_a				)

          lowercase    :				List[Any]       		=							model(_a	,    _a	,    attention_mask=_a	,    token_type_ids=_a				)
          self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.num_labels)				)
   def 			__magic_name__			(			self	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a				):
          lowercase    :				int       		=							self.num_labels
          lowercase    :				Dict       		=							TFLayoutLMForTokenClassification(config=_a				)

          lowercase    :				Tuple       		=							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 			__magic_name__			(			self	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a	,    _a				):
          lowercase    :				int       		=							TFLayoutLMForQuestionAnswering(config=_a				)

          lowercase    :				Any       		=							model(_a	,    _a	,    attention_mask=_a	,    token_type_ids=_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 			__magic_name__			(			self				):
          lowercase    :				Optional[int]       		=							self.prepare_config_and_inputs()
          (
              (
              lowercase
          )		,    (
              lowercase
          )		,    (
              lowercase
          )		,    (
              lowercase
          )		,    (
              lowercase
          )		,    (
              lowercase
          )		,    (
              lowercase
          )		,    (
              lowercase
          )		,    
          )    :				List[Any]       		=							config_and_inputs
          lowercase    :				int       		=							{
              "input_ids": input_ids,
              "bbox": bbox,
              "token_type_ids": token_type_ids,
              "attention_mask": input_mask,
          }
          return config, inputs_dict


@require_tf
class 		a__						(      a_,			a_,			unittest.TestCase						):
   __lowerCAmelCase            =				(
       (
           TFLayoutLMModel,
           TFLayoutLMForMaskedLM,
           TFLayoutLMForTokenClassification,
           TFLayoutLMForSequenceClassification,
           TFLayoutLMForQuestionAnswering,
       )
       if is_tf_available()
       else ()
   )
   __lowerCAmelCase            =				(
       {
           """feature-extraction""": TFLayoutLMModel,
           """fill-mask""": TFLayoutLMForMaskedLM,
           """text-classification""": TFLayoutLMForSequenceClassification,
           """token-classification""": TFLayoutLMForTokenClassification,
           """zero-shot""": TFLayoutLMForSequenceClassification,
       }
       if is_tf_available()
       else {}
   )
   __lowerCAmelCase            =				False
   __lowerCAmelCase            =				True
   __lowerCAmelCase            =				10
   def 			__magic_name__			(			self				):
          lowercase    :				List[Any]       		=							TFLayoutLMModelTester(self				)
          lowercase    :				List[Any]       		=							ConfigTester(self	,    config_class=_a	,    hidden_size=37				)
   def 			__magic_name__			(			self				):
          self.config_tester.run_common_tests()
   def 			__magic_name__			(			self				):
          lowercase    :				Tuple       		=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_a				)
   def 			__magic_name__			(			self				):
          lowercase    :				Dict       		=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_masked_lm(*_a				)
   def 			__magic_name__			(			self				):
          lowercase    :				List[Any]       		=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_sequence_classification(*_a				)
   def 			__magic_name__			(			self				):
          lowercase    :				Dict       		=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_token_classification(*_a				)
   def 			__magic_name__			(			self				):
          lowercase    :				str       		=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_question_answering(*_a				)
   @slow
   def 			__magic_name__			(			self				):
          for model_name in TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 lowercase    :				List[str]       		=							TFLayoutLMModel.from_pretrained(_a				)
                 self.assertIsNotNone(_a				)

   @unittest.skip("Onnx compliancy broke with TF 2.10"				)
   def 			__magic_name__			(			self				):
          pass


def   __magic_name__	(      ) ->				Optional[int]:
       # Here we prepare a batch of 2 sequences to test a LayoutLM forward pass on:
       # fmt: off
       lowercase    :				str       		=							tf.convert_to_tensor([[101,1019,1014,1016,1037,1_2849,4747,1004,1_4246,2278,5439,4524,5002,2930,2193,2930,4341,3208,1005,1055,2171,2848,1_1300,3531,102],[101,4070,4034,7020,1024,3058,1015,1013,2861,1013,6070,1_9274,2772,6205,2_7814,1_6147,1_6147,4343,2047,1_0283,1_0969,1_4389,1012,2338,102]]  )  # noqa: E231
       lowercase    :				Union[str, Any]       		=							tf.convert_to_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],]  )  # noqa: E231
       lowercase    :				Tuple       		=							tf.convert_to_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]]]  )  # noqa: E231
       lowercase    :				Optional[Any]       		=							tf.convert_to_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]]  )  # noqa: E231
       # these are sequence labels (i.e. at the token level)
       lowercase    :				List[Any]       		=							tf.convert_to_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]]  )  # noqa: E231
       # fmt: on

       return input_ids, attention_mask, bbox, token_type_ids, labels

@require_tf
class 		a__						(      unittest.TestCase						):
   @slow
   def 			__magic_name__			(			self				):
          lowercase    :				Dict       		=							TFLayoutLMModel.from_pretrained("microsoft/layoutlm-base-uncased"				)

          lowercase		,    lowercase		,    lowercase		,    lowercase		,    lowercase    :				Union[str, Any]       		=							prepare_layoutlm_batch_inputs()

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

          # test the sequence output on [0, :3, :3]
          lowercase    :				Any       		=							tf.convert_to_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]]	,    )

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

          # test the pooled output on [1, :3]
          lowercase    :				Optional[Any]       		=							tf.convert_to_tensor([-0.6_5_8_0, -0.0_2_1_4, 0.8_5_5_2]				)

          self.assertTrue(np.allclose(outputs.pooler_output[1, :3]	,    _a	,    atol=1E-3				)				)
   @slow
   def 			__magic_name__			(			self				):
          # initialize model with randomly initialized sequence classification head
          lowercase    :				List[Any]       		=							TFLayoutLMForSequenceClassification.from_pretrained("microsoft/layoutlm-base-uncased"	,    num_labels=2				)

          lowercase		,    lowercase		,    lowercase		,    lowercase		,    lowercase    :				Optional[Any]       		=							prepare_layoutlm_batch_inputs()

          # forward pass
          lowercase    :				Optional[Any]       		=							model(
              input_ids=_a	,    bbox=_a	,    attention_mask=_a	,    token_type_ids=_a	,    labels=tf.convert_to_tensor([1, 1]				)	,    )

          # test whether we get a loss as a scalar
          lowercase    :				Union[str, Any]       		=							outputs.loss
          lowercase    :				Union[str, Any]       		=							(2,)
          self.assertEqual(loss.shape	,    _a				)

          # test the shape of the logits
          lowercase    :				List[str]       		=							outputs.logits
          lowercase    :				Optional[Any]       		=							(2, 2)
          self.assertEqual(logits.shape	,    _a				)
   @slow
   def 			__magic_name__			(			self				):
          # initialize model with randomly initialized token classification head
          lowercase    :				Any       		=							TFLayoutLMForTokenClassification.from_pretrained("microsoft/layoutlm-base-uncased"	,    num_labels=13				)

          lowercase		,    lowercase		,    lowercase		,    lowercase		,    lowercase    :				str       		=							prepare_layoutlm_batch_inputs()

          # forward pass
          lowercase    :				List[Any]       		=							model(
              input_ids=_a	,    bbox=_a	,    attention_mask=_a	,    token_type_ids=_a	,    labels=_a				)

          # test the shape of the logits
          lowercase    :				int       		=							outputs.logits
          lowercase    :				Optional[Any]       		=							tf.convert_to_tensor((2, 25, 13)				)
          self.assertEqual(logits.shape	,    _a				)

   @slow
   def 			__magic_name__			(			self				):
          # initialize model with randomly initialized token classification head
          lowercase    :				Union[str, Any]       		=							TFLayoutLMForQuestionAnswering.from_pretrained("microsoft/layoutlm-base-uncased"				)

          lowercase		,    lowercase		,    lowercase		,    lowercase		,    lowercase    :				Tuple       		=							prepare_layoutlm_batch_inputs()

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

          # test the shape of the logits
          lowercase    :				Any       		=							tf.convert_to_tensor((2, 25)				)
          self.assertEqual(outputs.start_logits.shape	,    _a				)
          self.assertEqual(outputs.end_logits.shape	,    _a				)


