





import inspect
import unittest

from datasets import load_dataset
from packaging import version

from transformers import BeitConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch
    from torch import nn

    from transformers import (
        MODEL_MAPPING,
        BeitForImageClassification,
        BeitForMaskedImageModeling,
        BeitForSemanticSegmentation,
        BeitModel,
    )
    from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    import PIL
    from PIL import Image

    from transformers import BeitImageProcessor



class       A__     :





      def __init__(				self ,							A_ ,							A_=100 ,							A_=13 ,							A_=30 ,							A_=2 ,							A_=3 ,							A_=True ,							A_=True ,							A_=32 ,							A_=4 ,							A_=4 ,							A_=37 ,							A_="gelu" ,							A_=0.1 ,							A_=0.1 ,							A_=10 ,							A_=0.02 ,							A_=3 ,							A_=None ,							A_=[0, 1, 2, 3] ,							):
       '''simple docstring'''




       UpperCamelCase			:      int 			=     parent
       UpperCamelCase			:      Optional[Any] 			=     100
       UpperCamelCase			:      List[str] 			=     batch_size
       UpperCamelCase			:      int 			=     image_size
       UpperCamelCase			:      str 			=     patch_size
       UpperCamelCase			:      Optional[Any] 			=     num_channels
       UpperCamelCase			:      str 			=     is_training
       UpperCamelCase			:      Tuple 			=     use_labels
       UpperCamelCase			:      int 			=     hidden_size
       UpperCamelCase			:      Any 			=     num_hidden_layers
       UpperCamelCase			:      Union[str, Any] 			=     num_attention_heads
       UpperCamelCase			:      Dict 			=     intermediate_size
       UpperCamelCase			:      List[Any] 			=     hidden_act
       UpperCamelCase			:      Union[str, Any] 			=     hidden_dropout_prob
       UpperCamelCase			:      List[str] 			=     attention_probs_dropout_prob
       UpperCamelCase			:      Dict 			=     type_sequence_label_size
       UpperCamelCase			:      Union[str, Any] 			=     initializer_range
       UpperCamelCase			:      int 			=     scope
       UpperCamelCase			:      Optional[Any] 			=     out_indices
       UpperCamelCase			:      Tuple 			=     num_labels

       # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
       UpperCamelCase			:      List[str] 			=     (image_size // patch_size) ** 2
       UpperCamelCase			:      List[Any] 			=     num_patches + 1





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Union[str, Any] 			=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

       UpperCamelCase			:      int 			=     None
       UpperCamelCase			:      Optional[int] 			=     None
       if self.use_labels:
        UpperCamelCase			:      str 			=     ids_tensor([self.batch_size] ,							self.type_sequence_label_size     )
        UpperCamelCase			:      List[Any] 			=     ids_tensor([self.batch_size, self.image_size, self.image_size] ,							self.num_labels     )

       UpperCamelCase			:      int 			=     self.get_config()

       return config, pixel_values, labels, pixel_labels





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       return BeitConfig(
           vocab_size=self.vocab_size ,							image_size=self.image_size ,							patch_size=self.patch_size ,							num_channels=self.num_channels ,							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 ,							is_decoder=A_ ,							initializer_range=self.initializer_range ,							out_indices=self.out_indices ,							)





      def  __UpperCamelCase(				self ,							A_ ,							A_ ,							A_ ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      Dict 			=     BeitModel(config=A_     )
       model.to(A_     )
       model.eval()
       UpperCamelCase			:      Optional[Any] 			=     model(A_     )
       self.parent.assertEqual(result.last_hidden_state.shape ,							(self.batch_size, self.seq_length, self.hidden_size)     )





      def  __UpperCamelCase(				self ,							A_ ,							A_ ,							A_ ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      Any 			=     BeitForMaskedImageModeling(config=A_     )
       model.to(A_     )
       model.eval()
       UpperCamelCase			:      Dict 			=     model(A_     )
       self.parent.assertEqual(result.logits.shape ,							(self.batch_size, self.seq_length - 1, self.vocab_size)     )





      def  __UpperCamelCase(				self ,							A_ ,							A_ ,							A_ ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      Union[str, Any] 			=     self.type_sequence_label_size
       UpperCamelCase			:      List[Any] 			=     BeitForImageClassification(A_     )
       model.to(A_     )
       model.eval()
       UpperCamelCase			:      Tuple 			=     model(A_ ,							labels=A_     )
       self.parent.assertEqual(result.logits.shape ,							(self.batch_size, self.type_sequence_label_size)     )

       # test greyscale images
       UpperCamelCase			:      List[Any] 			=     1
       UpperCamelCase			:      Any 			=     BeitForImageClassification(A_     )
       model.to(A_     )
       model.eval()

       UpperCamelCase			:      int 			=     floats_tensor([self.batch_size, 1, self.image_size, self.image_size]     )
       UpperCamelCase			:      Tuple 			=     model(A_ ,							labels=A_     )
       self.parent.assertEqual(result.logits.shape ,							(self.batch_size, self.type_sequence_label_size)     )





      def  __UpperCamelCase(				self ,							A_ ,							A_ ,							A_ ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      Dict 			=     self.num_labels
       UpperCamelCase			:      List[str] 			=     BeitForSemanticSegmentation(A_     )
       model.to(A_     )
       model.eval()
       UpperCamelCase			:      int 			=     model(A_     )
       self.parent.assertEqual(
           result.logits.shape ,							(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)     )
       UpperCamelCase			:      Tuple 			=     model(A_ ,							labels=A_     )
       self.parent.assertEqual(
           result.logits.shape ,							(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Any 			=     self.prepare_config_and_inputs()
       UpperCamelCase			,					UpperCamelCase			,					UpperCamelCase			,					UpperCamelCase			:      Dict 			=     config_and_inputs
       UpperCamelCase			:      Optional[int] 			=     {"pixel_values": pixel_values}
       return config, inputs_dict



@require_torch
class       A__     ( __snake_case ,     __snake_case ,     unittest.TestCase    ):
      _UpperCAmelCase			:List[str]							=     (
          (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
          if is_torch_available()
          else ()
      )
      _UpperCAmelCase			:List[str]							=     (
          {
              'feature-extraction': BeitModel,
              'image-classification': BeitForImageClassification,
              'image-segmentation': BeitForSemanticSegmentation,
          }
          if is_torch_available()
          else {}
      )

      _UpperCAmelCase			:Optional[Any]							=     False
      _UpperCAmelCase			:str							=     False
      _UpperCAmelCase			:Optional[int]							=     False





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Optional[int] 			=     BeitModelTester(self     )
       UpperCamelCase			:      List[Any] 			=     ConfigTester(self ,							config_class=A_ ,							has_text_modality=A_ ,							hidden_size=37     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       self.config_tester.run_common_tests()





      @unittest.skip(reason="BEiT does not use inputs_embeds"     )
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       pass





      @require_torch_multi_gpu
      @unittest.skip(reason="BEiT has some layers using `add_module` which doesn't work well with `nn.DataParallel`"     )
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       pass





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			,					UpperCamelCase			:      str 			=     self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        UpperCamelCase			:      Tuple 			=     model_class(A_     )
        self.assertIsInstance(model.get_input_embeddings() ,							(nn.Module)     )
        UpperCamelCase			:      Dict 			=     model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(A_ ,							nn.Linear     )     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			,					UpperCamelCase			:      Optional[int] 			=     self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        UpperCamelCase			:      Optional[Any] 			=     model_class(A_     )
        UpperCamelCase			:      int 			=     inspect.signature(model.forward     )
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        UpperCamelCase			:      Optional[int] 			=     [*signature.parameters.keys()]

        UpperCamelCase			:      List[Any] 			=     ["pixel_values"]
        self.assertListEqual(arg_names[:1] ,							A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      List[str] 			=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Union[str, Any] 			=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_lm(*A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      List[str] 			=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      List[Any] 			=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_semantic_segmentation(*A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       if not self.model_tester.is_training:
        return

       UpperCamelCase			,					UpperCamelCase			:      Optional[Any] 			=     self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase			:      Dict 			=     True

       for model_class in self.all_model_classes:
        # we don't test BeitForMaskedImageModeling
        if model_class in [*get_values(A_     ), BeitForMaskedImageModeling]:
         continue

        UpperCamelCase			:      Dict 			=     model_class(A_     )
        model.to(A_     )
        model.train()
        UpperCamelCase			:      List[str] 			=     self._prepare_for_class(A_ ,							A_ ,							return_labels=A_     )
        UpperCamelCase			:      int 			=     model(**A_     ).loss
        loss.backward()





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			,					UpperCamelCase			:      Tuple 			=     self.model_tester.prepare_config_and_inputs_for_common()
       if not self.model_tester.is_training:
        return

       UpperCamelCase			:      List[Any] 			=     False
       UpperCamelCase			:      str 			=     True

       for model_class in self.all_model_classes:
        # we don't test BeitForMaskedImageModeling
        if (
            model_class in [*get_values(A_     ), BeitForMaskedImageModeling]
            or not model_class.supports_gradient_checkpointing
        ):
         continue

        UpperCamelCase			:      Union[str, Any] 			=     model_class(A_     )
        model.gradient_checkpointing_enable()
        model.to(A_     )
        model.train()
        UpperCamelCase			:      Optional[int] 			=     self._prepare_for_class(A_ ,							A_ ,							return_labels=A_     )
        UpperCamelCase			:      int 			=     model(**A_     ).loss
        loss.backward()





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			,					UpperCamelCase			:      Optional[Any] 			=     self.model_tester.prepare_config_and_inputs_for_common()

       UpperCamelCase			:      List[str] 			=     _config_zero_init(A_     )
       for model_class in self.all_model_classes:
        UpperCamelCase			:      Tuple 			=     model_class(config=A_     )
        for name, param in model.named_parameters():
         # we skip lambda parameters as these require special initial values
         # determined by config.layer_scale_init_value
         if "lambda" in name:
          continue
         if param.requires_grad:
          self.assertIn(
              ((param.data.mean() * 1e9).round() / 1e9).item() ,							[0.0, 1.0] ,							msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" ,							)





      @slow
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        UpperCamelCase			:      Dict 			=     BeitModel.from_pretrained(A_     )
        self.assertIsNotNone(A_     )



def 	A_       (  )		->				Optional[int]:
 UpperCamelCase			:      str 			=     Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  )
 return image



@require_torch
@require_vision
class       A__     ( unittest.TestCase    ):





      @cached_property
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       return BeitImageProcessor.from_pretrained("microsoft/beit-base-patch16-224"     ) if is_vision_available() else None





      @slow
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      str 			=     BeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k"     ).to(A_     )

       UpperCamelCase			:      int 			=     self.default_image_processor
       UpperCamelCase			:      int 			=     prepare_img()
       UpperCamelCase			:      Optional[int] 			=     image_processor(images=A_ ,							return_tensors="pt"     ).pixel_values.to(A_     )

       # prepare bool_masked_pos
       UpperCamelCase			:      Union[str, Any] 			=     torch.ones((1, 196) ,							dtype=torch.bool     ).to(A_     )

       # forward pass
       with torch.no_grad():
        UpperCamelCase			:      Optional[int] 			=     model(pixel_values=A_ ,							bool_masked_pos=A_     )
       UpperCamelCase			:      Any 			=     outputs.logits

       # verify the logits
       UpperCamelCase			:      List[str] 			=     torch.Size((1, 196, 8192)     )
       self.assertEqual(logits.shape ,							A_     )

       UpperCamelCase			:      List[Any] 			=     torch.tensor(
           [[-3.24_37, 0.50_72, -13.91_74], [-3.24_56, 0.49_48, -13.94_01], [-3.20_33, 0.51_21, -13.85_50]]     ).to(A_     )

       self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] ,							A_ ,							atol=1e-2     )     )





      @slow
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Any 			=     BeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224"     ).to(A_     )

       UpperCamelCase			:      List[Any] 			=     self.default_image_processor
       UpperCamelCase			:      Optional[Any] 			=     prepare_img()
       UpperCamelCase			:      int 			=     image_processor(images=A_ ,							return_tensors="pt"     ).to(A_     )

       # forward pass
       with torch.no_grad():
        UpperCamelCase			:      Any 			=     model(**A_     )
       UpperCamelCase			:      List[str] 			=     outputs.logits

       # verify the logits
       UpperCamelCase			:      Optional[int] 			=     torch.Size((1, 1000)     )
       self.assertEqual(logits.shape ,							A_     )

       UpperCamelCase			:      Optional[int] 			=     torch.tensor([-1.23_85, -1.09_87, -1.01_08]     ).to(A_     )

       self.assertTrue(torch.allclose(logits[0, :3] ,							A_ ,							atol=1e-4     )     )

       UpperCamelCase			:      Optional[int] 			=     281
       self.assertEqual(logits.argmax(-1     ).item() ,							A_     )





      @slow
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      List[str] 			=     BeitForImageClassification.from_pretrained("microsoft/beit-large-patch16-224-pt22k-ft22k"     ).to(
           A_     )

       UpperCamelCase			:      List[Any] 			=     self.default_image_processor
       UpperCamelCase			:      Union[str, Any] 			=     prepare_img()
       UpperCamelCase			:      Union[str, Any] 			=     image_processor(images=A_ ,							return_tensors="pt"     ).to(A_     )

       # forward pass
       with torch.no_grad():
        UpperCamelCase			:      Any 			=     model(**A_     )
       UpperCamelCase			:      Tuple 			=     outputs.logits

       # verify the logits
       UpperCamelCase			:      str 			=     torch.Size((1, 2_1841)     )
       self.assertEqual(logits.shape ,							A_     )

       UpperCamelCase			:      List[Any] 			=     torch.tensor([1.68_81, -0.27_87, 0.59_01]     ).to(A_     )

       self.assertTrue(torch.allclose(logits[0, :3] ,							A_ ,							atol=1e-4     )     )

       UpperCamelCase			:      Optional[int] 			=     2396
       self.assertEqual(logits.argmax(-1     ).item() ,							A_     )





      @slow
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Optional[int] 			=     BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640"     )
       UpperCamelCase			:      Optional[Any] 			=     model.to(A_     )

       UpperCamelCase			:      Dict 			=     BeitImageProcessor(do_resize=A_ ,							size=640 ,							do_center_crop=A_     )

       UpperCamelCase			:      List[str] 			=     load_dataset("hf-internal-testing/fixtures_ade20k" ,							split="test"     )
       UpperCamelCase			:      int 			=     Image.open(ds[0]["file"]     )
       UpperCamelCase			:      Any 			=     image_processor(images=A_ ,							return_tensors="pt"     ).to(A_     )

       # forward pass
       with torch.no_grad():
        UpperCamelCase			:      int 			=     model(**A_     )
       UpperCamelCase			:      Optional[int] 			=     outputs.logits

       # verify the logits
       UpperCamelCase			:      int 			=     torch.Size((1, 150, 160, 160)     )
       self.assertEqual(logits.shape ,							A_     )

       UpperCamelCase			:      Optional[Any] 			=     version.parse(PIL.__version__     ) < version.parse("9.0.0"     )

       if is_pillow_less_than_a:
        UpperCamelCase			:      Tuple 			=     torch.tensor(
            [
                [[-4.92_25, -2.39_54, -3.05_22], [-2.88_22, -1.00_46, -1.75_61], [-2.95_49, -1.32_28, -2.13_47]],
                [[-5.81_68, -3.41_29, -4.07_78], [-3.86_51, -2.22_14, -3.02_77], [-3.83_56, -2.46_43, -3.35_35]],
                [[-0.00_78, 3.99_52, 4.07_54], [2.98_56, 4.69_44, 5.00_35], [3.24_13, 4.78_13, 4.99_69]],
            ] ,							device=A_ ,							)
       else:
        UpperCamelCase			:      Optional[int] 			=     torch.tensor(
            [
                [[-4.89_60, -2.36_88, -3.03_55], [-2.84_78, -0.98_36, -1.74_18], [-2.94_49, -1.33_32, -2.14_56]],
                [[-5.80_81, -3.41_24, -4.10_06], [-3.85_61, -2.20_81, -3.03_23], [-3.83_65, -2.46_01, -3.36_69]],
                [[-0.03_09, 3.98_68, 4.05_40], [2.96_40, 4.68_77, 4.99_76], [3.20_81, 4.76_90, 4.99_42]],
            ] ,							device=A_ ,							)

       self.assertTrue(torch.allclose(logits[0, :3, :3, :3] ,							A_ ,							atol=1e-4     )     )





      @slow
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Optional[Any] 			=     BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640"     )
       UpperCamelCase			:      List[Any] 			=     model.to(A_     )

       UpperCamelCase			:      str 			=     BeitImageProcessor(do_resize=A_ ,							size=640 ,							do_center_crop=A_     )

       UpperCamelCase			:      Optional[Any] 			=     load_dataset("hf-internal-testing/fixtures_ade20k" ,							split="test"     )
       UpperCamelCase			:      List[Any] 			=     Image.open(ds[0]["file"]     )
       UpperCamelCase			:      List[Any] 			=     image_processor(images=A_ ,							return_tensors="pt"     ).to(A_     )

       # forward pass
       with torch.no_grad():
        UpperCamelCase			:      str 			=     model(**A_     )

       UpperCamelCase			:      List[Any] 			=     outputs.logits.detach().cpu()

       UpperCamelCase			:      Optional[Any] 			=     image_processor.post_process_semantic_segmentation(outputs=A_ ,							target_sizes=[(500, 300)]     )
       UpperCamelCase			:      int 			=     torch.Size((500, 300)     )
       self.assertEqual(segmentation[0].shape ,							A_     )

       UpperCamelCase			:      Any 			=     image_processor.post_process_semantic_segmentation(outputs=A_     )
       UpperCamelCase			:      List[Any] 			=     torch.Size((160, 160)     )
       self.assertEqual(segmentation[0].shape ,							A_     )







from __future__ import annotations

import os
import tempfile
import unittest

from transformers import ConvBertConfig, 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 import (
        TFConvBertForMaskedLM,
        TFConvBertForMultipleChoice,
        TFConvBertForQuestionAnswering,
        TFConvBertForSequenceClassification,
        TFConvBertForTokenClassification,
        TFConvBertModel,
    )



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.02 ,							A_=3 ,							A_=4 ,							A_=None ,							):
       '''simple docstring'''




       UpperCamelCase			:      Dict 			=     parent
       UpperCamelCase			:      str 			=     13
       UpperCamelCase			:      int 			=     7
       UpperCamelCase			:      str 			=     True
       UpperCamelCase			:      Dict 			=     True
       UpperCamelCase			:      str 			=     True
       UpperCamelCase			:      Tuple 			=     True
       UpperCamelCase			:      List[str] 			=     99
       UpperCamelCase			:      Optional[Any] 			=     384
       UpperCamelCase			:      Tuple 			=     2
       UpperCamelCase			:      Union[str, Any] 			=     4
       UpperCamelCase			:      Dict 			=     37
       UpperCamelCase			:      Any 			=     "gelu"
       UpperCamelCase			:      List[Any] 			=     0.1
       UpperCamelCase			:      int 			=     0.1
       UpperCamelCase			:      Tuple 			=     512
       UpperCamelCase			:      List[Any] 			=     16
       UpperCamelCase			:      int 			=     2
       UpperCamelCase			:      Dict 			=     0.02
       UpperCamelCase			:      Optional[Any] 			=     3
       UpperCamelCase			:      List[Any] 			=     4
       UpperCamelCase			:      Dict 			=     128
       UpperCamelCase			:      Optional[Any] 			=     2
       UpperCamelCase			:      Optional[int] 			=     9
       UpperCamelCase			:      Optional[int] 			=     1
       UpperCamelCase			:      Union[str, Any] 			=     None





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      int 			=     ids_tensor([self.batch_size, self.seq_length] ,							self.vocab_size     )

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

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

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

       UpperCamelCase			:      Any 			=     ConvBertConfig(
           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_dict=A_ ,							)

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





      def  __UpperCamelCase(				self ,							A_ ,							A_ ,							A_ ,							A_ ,							A_ ,							A_ ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      str 			=     TFConvBertModel(config=A_     )
       UpperCamelCase			:      Optional[Any] 			=     {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}

       UpperCamelCase			:      Optional[int] 			=     [input_ids, input_mask]
       UpperCamelCase			:      Any 			=     model(A_     )

       UpperCamelCase			:      int 			=     model(A_     )

       self.parent.assertEqual(result.last_hidden_state.shape ,							(self.batch_size, self.seq_length, self.hidden_size)     )





      def  __UpperCamelCase(				self ,							A_ ,							A_ ,							A_ ,							A_ ,							A_ ,							A_ ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      Tuple 			=     TFConvBertForMaskedLM(config=A_     )
       UpperCamelCase			:      int 			=     {
           "input_ids": input_ids,
           "attention_mask": input_mask,
           "token_type_ids": token_type_ids,
       }
       UpperCamelCase			:      Dict 			=     model(A_     )
       self.parent.assertEqual(result.logits.shape ,							(self.batch_size, self.seq_length, self.vocab_size)     )





      def  __UpperCamelCase(				self ,							A_ ,							A_ ,							A_ ,							A_ ,							A_ ,							A_ ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      Dict 			=     self.num_labels
       UpperCamelCase			:      int 			=     TFConvBertForSequenceClassification(config=A_     )
       UpperCamelCase			:      List[Any] 			=     {
           "input_ids": input_ids,
           "attention_mask": input_mask,
           "token_type_ids": token_type_ids,
       }

       UpperCamelCase			:      Optional[Any] 			=     model(A_     )
       self.parent.assertEqual(result.logits.shape ,							(self.batch_size, self.num_labels)     )





      def  __UpperCamelCase(				self ,							A_ ,							A_ ,							A_ ,							A_ ,							A_ ,							A_ ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      List[str] 			=     self.num_choices
       UpperCamelCase			:      str 			=     TFConvBertForMultipleChoice(config=A_     )
       UpperCamelCase			:      List[Any] 			=     tf.tile(tf.expand_dims(A_ ,							1     ) ,							(1, self.num_choices, 1)     )
       UpperCamelCase			:      Dict 			=     tf.tile(tf.expand_dims(A_ ,							1     ) ,							(1, self.num_choices, 1)     )
       UpperCamelCase			:      Any 			=     tf.tile(tf.expand_dims(A_ ,							1     ) ,							(1, self.num_choices, 1)     )
       UpperCamelCase			:      List[str] 			=     {
           "input_ids": multiple_choice_inputs_ids,
           "attention_mask": multiple_choice_input_mask,
           "token_type_ids": multiple_choice_token_type_ids,
       }
       UpperCamelCase			:      Optional[Any] 			=     model(A_     )
       self.parent.assertEqual(result.logits.shape ,							(self.batch_size, self.num_choices)     )





      def  __UpperCamelCase(				self ,							A_ ,							A_ ,							A_ ,							A_ ,							A_ ,							A_ ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      Dict 			=     self.num_labels
       UpperCamelCase			:      str 			=     TFConvBertForTokenClassification(config=A_     )
       UpperCamelCase			:      List[Any] 			=     {
           "input_ids": input_ids,
           "attention_mask": input_mask,
           "token_type_ids": token_type_ids,
       }
       UpperCamelCase			:      str 			=     model(A_     )
       self.parent.assertEqual(result.logits.shape ,							(self.batch_size, self.seq_length, self.num_labels)     )





      def  __UpperCamelCase(				self ,							A_ ,							A_ ,							A_ ,							A_ ,							A_ ,							A_ ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      List[str] 			=     TFConvBertForQuestionAnswering(config=A_     )
       UpperCamelCase			:      Union[str, Any] 			=     {
           "input_ids": input_ids,
           "attention_mask": input_mask,
           "token_type_ids": token_type_ids,
       }

       UpperCamelCase			:      Union[str, Any] 			=     model(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  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Optional[int] 			=     self.prepare_config_and_inputs()
       (
           (
           UpperCamelCase
       )			,					(
           UpperCamelCase
       )			,					(
           UpperCamelCase
       )			,					(
           UpperCamelCase
       )			,					(
           UpperCamelCase
       )			,					(
           UpperCamelCase
       )			,					(
           UpperCamelCase
       )			,					
       )			:      Optional[Any] 			=     config_and_inputs
       UpperCamelCase			:      int 			=     {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
       return config, inputs_dict



@require_tf
class       A__     ( __snake_case ,     __snake_case ,     unittest.TestCase    ):
      _UpperCAmelCase			:Dict							=     (
          (
              TFConvBertModel,
              TFConvBertForMaskedLM,
              TFConvBertForQuestionAnswering,
              TFConvBertForSequenceClassification,
              TFConvBertForTokenClassification,
              TFConvBertForMultipleChoice,
          )
          if is_tf_available()
          else ()
      )
      _UpperCAmelCase			:Optional[Any]							=     (
          {
              'feature-extraction': TFConvBertModel,
              'fill-mask': TFConvBertForMaskedLM,
              'question-answering': TFConvBertForQuestionAnswering,
              'text-classification': TFConvBertForSequenceClassification,
              'token-classification': TFConvBertForTokenClassification,
              'zero-shot': TFConvBertForSequenceClassification,
          }
          if is_tf_available()
          else {}
      )
      _UpperCAmelCase			:Any							=     False
      _UpperCAmelCase			:int							=     False
      _UpperCAmelCase			:str							=     False





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Dict 			=     TFConvBertModelTester(self     )
       UpperCamelCase			:      Dict 			=     ConfigTester(self ,							config_class=A_ ,							hidden_size=37     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       self.config_tester.run_common_tests()





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Dict 			=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Dict 			=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_lm(*A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      List[str] 			=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_multiple_choice(*A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      List[str] 			=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_question_answering(*A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Tuple 			=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_sequence_classification(*A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Optional[Any] 			=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_token_classification(*A_     )





      @slow
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			,					UpperCamelCase			:      Dict 			=     self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase			:      Optional[Any] 			=     True
       UpperCamelCase			:      Any 			=     True

       if hasattr(A_ ,							"use_cache"     ):
        UpperCamelCase			:      List[str] 			=     True

       UpperCamelCase			:      List[Any] 			=     getattr(self.model_tester ,							"encoder_seq_length" ,							self.model_tester.seq_length     )
       UpperCamelCase			:      Any 			=     getattr(self.model_tester ,							"key_length" ,							A_     )

       for model_class in self.all_model_classes:
        UpperCamelCase			:      List[Any] 			=     self._prepare_for_class(A_ ,							A_     )
        UpperCamelCase			:      Dict 			=     model_class(A_     )
        UpperCamelCase			:      Optional[int] 			=     len(model(A_     )     )

        with tempfile.TemporaryDirectory() as tmpdirname:
         model.save_pretrained(A_ ,							saved_model=A_     )
         UpperCamelCase			:      Union[str, Any] 			=     os.path.join(A_ ,							"saved_model" ,							"1"     )
         UpperCamelCase			:      Dict 			=     tf.keras.models.load_model(A_     )
         UpperCamelCase			:      str 			=     model(A_     )

         if self.is_encoder_decoder:
          UpperCamelCase			:      Union[str, Any] 			=     outputs["encoder_hidden_states"]
          UpperCamelCase			:      Any 			=     outputs["encoder_attentions"]
         else:
          UpperCamelCase			:      Any 			=     outputs["hidden_states"]
          UpperCamelCase			:      List[str] 			=     outputs["attentions"]

         self.assertEqual(len(A_     ) ,							A_     )

         UpperCamelCase			:      int 			=     getattr(
             self.model_tester ,							"expected_num_hidden_layers" ,							self.model_tester.num_hidden_layers + 1     )

         self.assertEqual(len(A_     ) ,							A_     )
         self.assertListEqual(
             list(output_hidden_states[0].shape[-2:]     ) ,							[self.model_tester.seq_length, self.model_tester.hidden_size] ,							)

         self.assertEqual(len(A_     ) ,							self.model_tester.num_hidden_layers     )
         self.assertListEqual(
             list(output_attentions[0].shape[-3:]     ) ,							[self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] ,							)





      @slow
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Union[str, Any] 			=     TFConvBertModel.from_pretrained("YituTech/conv-bert-base"     )
       self.assertIsNotNone(A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			,					UpperCamelCase			:      Tuple 			=     self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase			:      Dict 			=     True
       UpperCamelCase			:      int 			=     getattr(self.model_tester ,							"decoder_seq_length" ,							self.model_tester.seq_length     )
       UpperCamelCase			:      Optional[int] 			=     getattr(self.model_tester ,							"encoder_seq_length" ,							self.model_tester.seq_length     )
       UpperCamelCase			:      Optional[int] 			=     getattr(self.model_tester ,							"key_length" ,							A_     )
       UpperCamelCase			:      Optional[Any] 			=     getattr(self.model_tester ,							"key_length" ,							A_     )

       def check_decoder_attentions_output(A_     ):
        UpperCamelCase			:      Optional[Any] 			=     len(A_     )
        self.assertEqual(out_len % 2 ,							0     )
        UpperCamelCase			:      Any 			=     outputs.decoder_attentions
        self.assertEqual(len(A_     ) ,							self.model_tester.num_hidden_layers     )
        self.assertListEqual(
            list(decoder_attentions[0].shape[-3:]     ) ,							[self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] ,							)

       def check_encoder_attentions_output(A_     ):
        UpperCamelCase			:      Dict 			=     [
            t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions)
        ]
        self.assertEqual(len(A_     ) ,							self.model_tester.num_hidden_layers     )
        self.assertListEqual(
            list(attentions[0].shape[-3:]     ) ,							[self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] ,							)

       for model_class in self.all_model_classes:
        UpperCamelCase			:      Union[str, Any] 			=     True
        UpperCamelCase			:      List[Any] 			=     False
        UpperCamelCase			:      Dict 			=     model_class(A_     )
        UpperCamelCase			:      Dict 			=     model(self._prepare_for_class(A_ ,							A_     )     )
        UpperCamelCase			:      List[str] 			=     len(A_     )
        self.assertEqual(config.output_hidden_states ,							A_     )
        check_encoder_attentions_output(A_     )

        if self.is_encoder_decoder:
         UpperCamelCase			:      int 			=     model_class(A_     )
         UpperCamelCase			:      Tuple 			=     model(self._prepare_for_class(A_ ,							A_     )     )
         self.assertEqual(config.output_hidden_states ,							A_     )
         check_decoder_attentions_output(A_     )

        # Check that output attentions can also be changed via the config
        del inputs_dict["output_attentions"]
        UpperCamelCase			:      Tuple 			=     True
        UpperCamelCase			:      int 			=     model_class(A_     )
        UpperCamelCase			:      Dict 			=     model(self._prepare_for_class(A_ ,							A_     )     )
        self.assertEqual(config.output_hidden_states ,							A_     )
        check_encoder_attentions_output(A_     )

        # Check attention is always last and order is fine
        UpperCamelCase			:      Optional[int] 			=     True
        UpperCamelCase			:      List[str] 			=     True
        UpperCamelCase			:      Optional[int] 			=     model_class(A_     )
        UpperCamelCase			:      Optional[Any] 			=     model(self._prepare_for_class(A_ ,							A_     )     )

        self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) ,							len(A_     )     )
        self.assertEqual(model.config.output_hidden_states ,							A_     )
        check_encoder_attentions_output(A_     )



@require_tf
class       A__     ( unittest.TestCase    ):





      @slow
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      str 			=     TFConvBertModel.from_pretrained("YituTech/conv-bert-base"     )
       UpperCamelCase			:      str 			=     tf.constant([[0, 1, 2, 3, 4, 5]]     )
       UpperCamelCase			:      List[str] 			=     model(A_     )[0]

       UpperCamelCase			:      int 			=     [1, 6, 768]
       self.assertEqual(output.shape ,							A_     )

       UpperCamelCase			:      List[str] 			=     tf.constant(
           [
               [
                   [-0.03_47_54_93, -0.4_68_60_34, -0.30_63_88_32],
                   [0.22_63_72_48, -0.26_98_86_46, -0.7_42_34_24],
                   [0.10_32_48_68, -0.45_01_35_08, -0.58_28_07_84],
               ]
           ]     )
       tf.debugging.assert_near(output[:, :3, :3] ,							A_ ,							atol=1e-4     )
