






'''simple docstring'''







import collections
import inspect
import unittest

from transformers import FocalNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
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 (
		    FocalNetBackbone,
		    FocalNetForImageClassification,
		    FocalNetForMaskedImageModeling,
		    FocalNetModel,
		)
		from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor





class 						SCREAMING_SNAKE_CASE       :






			def __init__(			self   :      Optional[Any]	,    __SCREAMING_SNAKE_CASE   :      str	,    __SCREAMING_SNAKE_CASE   :      Tuple=13	,    __SCREAMING_SNAKE_CASE   :      Union[str, Any]=32	,    __SCREAMING_SNAKE_CASE   :      List[Any]=2	,    __SCREAMING_SNAKE_CASE   :      Any=3	,    __SCREAMING_SNAKE_CASE   :      Optional[Any]=16	,    __SCREAMING_SNAKE_CASE   :      Tuple=[32, 64, 128]	,    __SCREAMING_SNAKE_CASE   :      Dict=[1, 2, 1]	,    __SCREAMING_SNAKE_CASE   :      Any=[2, 2, 4]	,    __SCREAMING_SNAKE_CASE   :      Optional[Any]=2	,    __SCREAMING_SNAKE_CASE   :      Optional[Any]=2.0	,    __SCREAMING_SNAKE_CASE   :      Tuple=True	,    __SCREAMING_SNAKE_CASE   :      Union[str, Any]=0.0	,    __SCREAMING_SNAKE_CASE   :      str=0.0	,    __SCREAMING_SNAKE_CASE   :      str=0.1	,    __SCREAMING_SNAKE_CASE   :      List[Any]="gelu"	,    __SCREAMING_SNAKE_CASE   :      Optional[Any]=False	,    __SCREAMING_SNAKE_CASE   :      List[str]=True	,    __SCREAMING_SNAKE_CASE   :      List[str]=0.02	,    __SCREAMING_SNAKE_CASE   :      Tuple=1e-5	,    __SCREAMING_SNAKE_CASE   :      Dict=True	,    __SCREAMING_SNAKE_CASE   :      Tuple=None	,    __SCREAMING_SNAKE_CASE   :      Union[str, Any]=True	,    __SCREAMING_SNAKE_CASE   :      List[Any]=10	,    __SCREAMING_SNAKE_CASE   :      Tuple=8	,    __SCREAMING_SNAKE_CASE   :      Dict=["stage1", "stage2"]	,    __SCREAMING_SNAKE_CASE   :      List[Any]=[1, 2]	,    )      ->      Dict:
							a_		:	Any									=   parent
							a_		:	str									=   batch_size
							a_		:	Optional[int]									=   image_size
							a_		:	Any									=   patch_size
							a_		:	Optional[int]									=   num_channels
							a_		:	Any									=   embed_dim
							a_		:	Dict									=   hidden_sizes
							a_		:	Tuple									=   depths
							a_		:	Union[str, Any]									=   num_heads
							a_		:	Optional[Any]									=   window_size
							a_		:	Union[str, Any]									=   mlp_ratio
							a_		:	Optional[Any]									=   qkv_bias
							a_		:	int									=   hidden_dropout_prob
							a_		:	List[str]									=   attention_probs_dropout_prob
							a_		:	Tuple									=   drop_path_rate
							a_		:	str									=   hidden_act
							a_		:	Tuple									=   use_absolute_embeddings
							a_		:	Any									=   patch_norm
							a_		:	Dict									=   layer_norm_eps
							a_		:	Tuple									=   initializer_range
							a_		:	Any									=   is_training
							a_		:	Union[str, Any]									=   scope
							a_		:	str									=   use_labels
							a_		:	Union[str, Any]									=   type_sequence_label_size
							a_		:	Optional[Any]									=   encoder_stride
							a_		:	List[Any]									=   out_features
							a_		:	Optional[int]									=   out_indices






			def       SCREAMING_SNAKE_CASE   (			self   :      Optional[Any]       )      ->      List[Any]:
							a_		:	List[str]									=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

							a_		:	Dict									=   None
							if self.use_labels:
											a_		:	List[str]									=   ids_tensor([self.batch_size]	,    self.type_sequence_label_size       )

							a_		:	Union[str, Any]									=   self.get_config()

							return config, pixel_values, labels






			def       SCREAMING_SNAKE_CASE   (			self   :      List[Any]       )      ->      Any:
							return FocalNetConfig(
							    image_size=self.image_size	,    patch_size=self.patch_size	,    num_channels=self.num_channels	,    embed_dim=self.embed_dim	,    hidden_sizes=self.hidden_sizes	,    depths=self.depths	,    num_heads=self.num_heads	,    window_size=self.window_size	,    mlp_ratio=self.mlp_ratio	,    qkv_bias=self.qkv_bias	,    hidden_dropout_prob=self.hidden_dropout_prob	,    attention_probs_dropout_prob=self.attention_probs_dropout_prob	,    drop_path_rate=self.drop_path_rate	,    hidden_act=self.hidden_act	,    use_absolute_embeddings=self.use_absolute_embeddings	,    path_norm=self.patch_norm	,    layer_norm_eps=self.layer_norm_eps	,    initializer_range=self.initializer_range	,    encoder_stride=self.encoder_stride	,    out_features=self.out_features	,    out_indices=self.out_indices	,    )






			def       SCREAMING_SNAKE_CASE   (			self   :      List[Any]	,    __SCREAMING_SNAKE_CASE   :      List[str]	,    __SCREAMING_SNAKE_CASE   :      Union[str, Any]	,    __SCREAMING_SNAKE_CASE   :      List[Any]       )      ->      Optional[int]:
							a_		:	Optional[int]									=   FocalNetModel(config=__SCREAMING_SNAKE_CASE       )
							model.to(__SCREAMING_SNAKE_CASE       )
							model.eval()
							a_		:	Dict									=   model(__SCREAMING_SNAKE_CASE       )

							a_		:	int									=   ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths       ) - 1))
							a_		:	Dict									=   int(config.embed_dim * 2 ** (len(config.depths       ) - 1)       )

							self.parent.assertEqual(result.last_hidden_state.shape	,    (self.batch_size, expected_seq_len, expected_dim)       )






			def       SCREAMING_SNAKE_CASE   (			self   :      Union[str, Any]	,    __SCREAMING_SNAKE_CASE   :      str	,    __SCREAMING_SNAKE_CASE   :      Optional[int]	,    __SCREAMING_SNAKE_CASE   :      Dict       )      ->      List[Any]:
							a_		:	int									=   FocalNetBackbone(config=__SCREAMING_SNAKE_CASE       )
							model.to(__SCREAMING_SNAKE_CASE       )
							model.eval()
							a_		:	Any									=   model(__SCREAMING_SNAKE_CASE       )

							# verify feature maps
							self.parent.assertEqual(len(result.feature_maps       )	,    len(config.out_features       )       )
							self.parent.assertListEqual(list(result.feature_maps[0].shape       )	,    [self.batch_size, self.image_size, 8, 8]       )

							# verify channels
							self.parent.assertEqual(len(model.channels       )	,    len(config.out_features       )       )
							self.parent.assertListEqual(model.channels	,    config.hidden_sizes[:-1]       )

							# verify backbone works with out_features=None
							a_		:	List[str]									=   None
							a_		:	str									=   FocalNetBackbone(config=__SCREAMING_SNAKE_CASE       )
							model.to(__SCREAMING_SNAKE_CASE       )
							model.eval()
							a_		:	Any									=   model(__SCREAMING_SNAKE_CASE       )

							# verify feature maps
							self.parent.assertEqual(len(result.feature_maps       )	,    1       )
							self.parent.assertListEqual(list(result.feature_maps[0].shape       )	,    [self.batch_size, self.image_size * 2, 4, 4]       )

							# verify channels
							self.parent.assertEqual(len(model.channels       )	,    1       )
							self.parent.assertListEqual(model.channels	,    [config.hidden_sizes[-1]]       )






			def       SCREAMING_SNAKE_CASE   (			self   :      Any	,    __SCREAMING_SNAKE_CASE   :      int	,    __SCREAMING_SNAKE_CASE   :      Dict	,    __SCREAMING_SNAKE_CASE   :      Tuple       )      ->      Tuple:
							a_		:	Union[str, Any]									=   FocalNetForMaskedImageModeling(config=__SCREAMING_SNAKE_CASE       )
							model.to(__SCREAMING_SNAKE_CASE       )
							model.eval()
							a_		:	List[Any]									=   model(__SCREAMING_SNAKE_CASE       )
							self.parent.assertEqual(
							    result.reconstruction.shape	,    (self.batch_size, self.num_channels, self.image_size, self.image_size)       )

							# test greyscale images
							a_		:	str									=   1
							a_		:	Any									=   FocalNetForMaskedImageModeling(__SCREAMING_SNAKE_CASE       )
							model.to(__SCREAMING_SNAKE_CASE       )
							model.eval()

							a_		:	List[str]									=   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
							a_		:	Optional[int]									=   model(__SCREAMING_SNAKE_CASE       )
							self.parent.assertEqual(result.reconstruction.shape	,    (self.batch_size, 1, self.image_size, self.image_size)       )






			def       SCREAMING_SNAKE_CASE   (			self   :      Tuple	,    __SCREAMING_SNAKE_CASE   :      str	,    __SCREAMING_SNAKE_CASE   :      List[Any]	,    __SCREAMING_SNAKE_CASE   :      Any       )      ->      Optional[int]:
							a_		:	Dict									=   self.type_sequence_label_size
							a_		:	Any									=   FocalNetForImageClassification(__SCREAMING_SNAKE_CASE       )
							model.to(__SCREAMING_SNAKE_CASE       )
							model.eval()
							a_		:	List[Any]									=   model(__SCREAMING_SNAKE_CASE	,    labels=__SCREAMING_SNAKE_CASE       )
							self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.type_sequence_label_size)       )

							# test greyscale images
							a_		:	Union[str, Any]									=   1
							a_		:	Any									=   FocalNetForImageClassification(__SCREAMING_SNAKE_CASE       )
							model.to(__SCREAMING_SNAKE_CASE       )
							model.eval()

							a_		:	Dict									=   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
							a_		:	Union[str, Any]									=   model(__SCREAMING_SNAKE_CASE       )
							self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.type_sequence_label_size)       )







			def       SCREAMING_SNAKE_CASE   (			self   :      List[str]       )      ->      Optional[Any]:
							a_		:	Optional[int]									=   self.prepare_config_and_inputs()

							a_					,      a_					,      a_		:	List[str]									=   config_and_inputs
							a_		:	Union[str, Any]									=   {'''pixel_values''': pixel_values}
							return config, inputs_dict





@require_torch
class 						SCREAMING_SNAKE_CASE       (       SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_						, unittest.TestCase							):
			snake_case__	=					(
			    (
			        FocalNetModel,
			        FocalNetForImageClassification,
			        FocalNetForMaskedImageModeling,
			        FocalNetBackbone,
			    )
			    if is_torch_available()
			    else ()
			)
			snake_case__	=					(
			    {"feature-extraction": FocalNetModel, "image-classification": FocalNetForImageClassification}
			    if is_torch_available()
			    else {}
			)
			snake_case__	=					False

			snake_case__	=					False
			snake_case__	=					False
			snake_case__	=					False
			snake_case__	=					False






			def       SCREAMING_SNAKE_CASE   (			self   :      List[str]       )      ->      Tuple:
							a_		:	Tuple									=   FocalNetModelTester(self       )
							a_		:	int									=   ConfigTester(self	,    config_class=__SCREAMING_SNAKE_CASE	,    embed_dim=37	,    has_text_modality=__SCREAMING_SNAKE_CASE       )






			def       SCREAMING_SNAKE_CASE   (			self   :      Optional[Any]       )      ->      Optional[Any]:
							self.create_and_test_config_common_properties()
							self.config_tester.create_and_test_config_to_json_string()
							self.config_tester.create_and_test_config_to_json_file()
							self.config_tester.create_and_test_config_from_and_save_pretrained()
							self.config_tester.create_and_test_config_with_num_labels()
							self.config_tester.check_config_can_be_init_without_params()
							self.config_tester.check_config_arguments_init()






			def       SCREAMING_SNAKE_CASE   (			self   :      str       )      ->      Dict:
							return






			def       SCREAMING_SNAKE_CASE   (			self   :      Optional[Any]       )      ->      Tuple:
							a_		:	Dict									=   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE       )






			def       SCREAMING_SNAKE_CASE   (			self   :      Optional[Any]       )      ->      Optional[Any]:
							a_		:	Tuple									=   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_backbone(*__SCREAMING_SNAKE_CASE       )






			def       SCREAMING_SNAKE_CASE   (			self   :      List[str]       )      ->      Dict:
							a_		:	Any									=   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_image_modeling(*__SCREAMING_SNAKE_CASE       )






			def       SCREAMING_SNAKE_CASE   (			self   :      str       )      ->      Optional[Any]:
							a_		:	Union[str, Any]									=   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE       )






			@unittest.skip(reason='''FocalNet does not use inputs_embeds'''       )
			def       SCREAMING_SNAKE_CASE   (			self   :      Optional[int]       )      ->      Optional[int]:
							pass






			@unittest.skip(reason='''FocalNet does not use feedforward chunking'''       )
			def       SCREAMING_SNAKE_CASE   (			self   :      Union[str, Any]       )      ->      Optional[Any]:
							pass






			def       SCREAMING_SNAKE_CASE   (			self   :      Union[str, Any]       )      ->      Optional[Any]:
							a_					,      a_		:	Any									=   self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes[:-1]:
											a_		:	List[str]									=   model_class(__SCREAMING_SNAKE_CASE       )
											self.assertIsInstance(model.get_input_embeddings()	,    (nn.Module)       )
											a_		:	List[str]									=   model.get_output_embeddings()
											self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE	,    nn.Linear       )       )






			def       SCREAMING_SNAKE_CASE   (			self   :      Optional[int]       )      ->      List[Any]:
							a_					,      a_		:	int									=   self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes[:-1]:
											a_		:	Optional[Any]									=   model_class(__SCREAMING_SNAKE_CASE       )
											a_		:	Optional[Any]									=   inspect.signature(model.forward       )
											# signature.parameters is an OrderedDict => so arg_names order is deterministic
											a_		:	Union[str, Any]									=   [*signature.parameters.keys()]

											a_		:	Any									=   ['''pixel_values''']
											self.assertListEqual(arg_names[:1]	,    __SCREAMING_SNAKE_CASE       )






			def       SCREAMING_SNAKE_CASE   (			self   :      str	,    __SCREAMING_SNAKE_CASE   :      Any	,    __SCREAMING_SNAKE_CASE   :      int	,    __SCREAMING_SNAKE_CASE   :      List[Any]	,    __SCREAMING_SNAKE_CASE   :      Dict       )      ->      Any:
							a_		:	int									=   model_class(__SCREAMING_SNAKE_CASE       )
							model.to(__SCREAMING_SNAKE_CASE       )
							model.eval()

							with torch.no_grad():
											a_		:	int									=   model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE       )       )

							a_		:	List[Any]									=   outputs.hidden_states

							a_		:	int									=   getattr(
							    self.model_tester	,    '''expected_num_hidden_layers'''	,    len(self.model_tester.depths       ) + 1       )
							self.assertEqual(len(__SCREAMING_SNAKE_CASE       )	,    __SCREAMING_SNAKE_CASE       )

							# FocalNet has a different seq_length
							a_		:	Union[str, Any]									=   (
							    config.patch_size
							    if isinstance(config.patch_size	,    collections.abc.Iterable       )
							    else (config.patch_size, config.patch_size)
							)

							a_		:	Tuple									=   (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

							self.assertListEqual(
							    list(hidden_states[0].shape[-2:]       )	,    [num_patches, self.model_tester.embed_dim]	,    )

							a_		:	List[Any]									=   outputs.reshaped_hidden_states
							self.assertEqual(len(__SCREAMING_SNAKE_CASE       )	,    __SCREAMING_SNAKE_CASE       )

							a_					,      a_					,      a_					,      a_		:	Dict									=   reshaped_hidden_states[0].shape
							a_		:	str									=   (
							    reshaped_hidden_states[0].view(__SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE	,    height * width       ).permute(0	,    2	,    1       )
							)
							self.assertListEqual(
							    list(reshaped_hidden_states.shape[-2:]       )	,    [num_patches, self.model_tester.embed_dim]	,    )






			def       SCREAMING_SNAKE_CASE   (			self   :      List[Any]       )      ->      Tuple:
							a_					,      a_		:	Optional[Any]									=   self.model_tester.prepare_config_and_inputs_for_common()

							a_		:	Any									=   (
							    self.model_tester.image_size
							    if isinstance(self.model_tester.image_size	,    collections.abc.Iterable       )
							    else (self.model_tester.image_size, self.model_tester.image_size)
							)

							for model_class in self.all_model_classes[:-1]:
											a_		:	Optional[int]									=   True
											self.check_hidden_states_output(__SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE       )

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											a_		:	Tuple									=   True

											self.check_hidden_states_output(__SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE       )






			def       SCREAMING_SNAKE_CASE   (			self   :      Optional[int]       )      ->      Union[str, Any]:
							a_					,      a_		:	Union[str, Any]									=   self.model_tester.prepare_config_and_inputs_for_common()
							a_		:	Union[str, Any]									=   3

							a_		:	Tuple									=   (
							    self.model_tester.image_size
							    if isinstance(self.model_tester.image_size	,    collections.abc.Iterable       )
							    else (self.model_tester.image_size, self.model_tester.image_size)
							)
							a_		:	Dict									=   (
							    config.patch_size
							    if isinstance(config.patch_size	,    collections.abc.Iterable       )
							    else (config.patch_size, config.patch_size)
							)

							a_		:	Optional[int]									=   image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
							a_		:	Optional[int]									=   image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

							for model_class in self.all_model_classes[:-1]:
											a_		:	Optional[Any]									=   True
											self.check_hidden_states_output(__SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE	,    (padded_height, padded_width)       )

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											a_		:	Dict									=   True
											self.check_hidden_states_output(__SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE	,    (padded_height, padded_width)       )






			@slow
			def       SCREAMING_SNAKE_CASE   (			self   :      Any       )      ->      int:
							for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											a_		:	Optional[Any]									=   FocalNetModel.from_pretrained(__SCREAMING_SNAKE_CASE       )
											self.assertIsNotNone(__SCREAMING_SNAKE_CASE       )







			def       SCREAMING_SNAKE_CASE   (			self   :      Tuple       )      ->      List[Any]:
							a_					,      a_		:	Any									=   self.model_tester.prepare_config_and_inputs_for_common()

							a_		:	Optional[Any]									=   _config_zero_init(__SCREAMING_SNAKE_CASE       )
							for model_class in self.all_model_classes:
											a_		:	Optional[int]									=   model_class(config=__SCREAMING_SNAKE_CASE       )
											for name, param in model.named_parameters():
															if "embeddings" not in name and 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'	,    )





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






			@cached_property
			def       SCREAMING_SNAKE_CASE   (			self   :      str       )      ->      Tuple:
							# TODO update organization
							return AutoImageProcessor.from_pretrained('''microsoft/focalnet-tiny'''       ) if is_vision_available() else None







			@slow
			def       SCREAMING_SNAKE_CASE   (			self   :      str       )      ->      str:
							a_		:	Optional[Any]									=   FocalNetForImageClassification.from_pretrained('''microsoft/focalnet-tiny'''       ).to(__SCREAMING_SNAKE_CASE       )
							a_		:	List[str]									=   self.default_image_processor

							a_		:	Union[str, Any]									=   Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''       )
							a_		:	int									=   image_processor(images=__SCREAMING_SNAKE_CASE	,    return_tensors='''pt'''       ).to(__SCREAMING_SNAKE_CASE       )

							# forward pass
							with torch.no_grad():
											a_		:	Any									=   model(**__SCREAMING_SNAKE_CASE       )

							# verify the logits
							a_		:	Union[str, Any]									=   torch.Size((1, 1000)       )
							self.assertEqual(outputs.logits.shape	,    __SCREAMING_SNAKE_CASE       )
							a_		:	Dict									=   torch.tensor([0.2166, -0.4368, 0.2191]       ).to(__SCREAMING_SNAKE_CASE       )
							self.assertTrue(torch.allclose(outputs.logits[0, :3]	,    __SCREAMING_SNAKE_CASE	,    atol=1e-4       )       )
							self.assertTrue(outputs.logits.argmax(dim=-1       ).item()	,    281       )





@require_torch
class 						SCREAMING_SNAKE_CASE       (       SCREAMING_SNAKE_CASE_						, unittest.TestCase							):
			snake_case__	=					(FocalNetBackbone,) if is_torch_available() else ()
			snake_case__	=					FocalNetConfig

			snake_case__	=					False






			def       SCREAMING_SNAKE_CASE   (			self   :      Any       )      ->      List[str]:
							a_		:	Any									=   FocalNetModelTester(self       )












'''simple docstring'''







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






			def __init__(			self   :      Union[str, Any]	,    __SCREAMING_SNAKE_CASE   :      Tuple	,    __SCREAMING_SNAKE_CASE   :      str=13	,    __SCREAMING_SNAKE_CASE   :      Optional[int]=7	,    __SCREAMING_SNAKE_CASE   :      List[str]=True	,    __SCREAMING_SNAKE_CASE   :      Optional[int]=True	,    __SCREAMING_SNAKE_CASE   :      Any=True	,    __SCREAMING_SNAKE_CASE   :      int=True	,    __SCREAMING_SNAKE_CASE   :      List[str]=99	,    __SCREAMING_SNAKE_CASE   :      Optional[int]=32	,    __SCREAMING_SNAKE_CASE   :      Tuple=2	,    __SCREAMING_SNAKE_CASE   :      str=4	,    __SCREAMING_SNAKE_CASE   :      int=37	,    __SCREAMING_SNAKE_CASE   :      Any="gelu"	,    __SCREAMING_SNAKE_CASE   :      List[Any]=0.1	,    __SCREAMING_SNAKE_CASE   :      List[Any]=0.1	,    __SCREAMING_SNAKE_CASE   :      Tuple=512	,    __SCREAMING_SNAKE_CASE   :      Optional[Any]=16	,    __SCREAMING_SNAKE_CASE   :      Dict=2	,    __SCREAMING_SNAKE_CASE   :      List[Any]=0.02	,    __SCREAMING_SNAKE_CASE   :      List[Any]=3	,    __SCREAMING_SNAKE_CASE   :      List[Any]=4	,    __SCREAMING_SNAKE_CASE   :      Dict=None	,    )      ->      Tuple:
							a_		:	Any									=   parent
							a_		:	List[str]									=   13
							a_		:	Dict									=   7
							a_		:	List[str]									=   True
							a_		:	str									=   True
							a_		:	List[str]									=   True
							a_		:	Any									=   True
							a_		:	List[Any]									=   99
							a_		:	Optional[Any]									=   384
							a_		:	List[str]									=   2
							a_		:	Optional[int]									=   4
							a_		:	Optional[int]									=   37
							a_		:	Union[str, Any]									=   '''gelu'''
							a_		:	List[str]									=   0.1
							a_		:	str									=   0.1
							a_		:	Optional[Any]									=   512
							a_		:	Union[str, Any]									=   16
							a_		:	Optional[Any]									=   2
							a_		:	Optional[int]									=   0.02
							a_		:	Union[str, Any]									=   3
							a_		:	Union[str, Any]									=   4
							a_		:	List[Any]									=   128
							a_		:	Optional[Any]									=   2
							a_		:	Any									=   9
							a_		:	Optional[int]									=   1
							a_		:	int									=   None






			def       SCREAMING_SNAKE_CASE   (			self   :      Dict       )      ->      Union[str, Any]:
							a_		:	Dict									=   ids_tensor([self.batch_size, self.seq_length]	,    self.vocab_size       )

							a_		:	int									=   None
							if self.use_input_mask:
											a_		:	Dict									=   random_attention_mask([self.batch_size, self.seq_length]       )

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

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

							a_		:	Union[str, 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=__SCREAMING_SNAKE_CASE	,    )

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






			def       SCREAMING_SNAKE_CASE   (			self   :      Optional[Any]	,    __SCREAMING_SNAKE_CASE   :      Any	,    __SCREAMING_SNAKE_CASE   :      Tuple	,    __SCREAMING_SNAKE_CASE   :      Any	,    __SCREAMING_SNAKE_CASE   :      Any	,    __SCREAMING_SNAKE_CASE   :      int	,    __SCREAMING_SNAKE_CASE   :      Any	,    __SCREAMING_SNAKE_CASE   :      Optional[Any]       )      ->      Union[str, Any]:
							a_		:	Tuple									=   TFConvBertModel(config=__SCREAMING_SNAKE_CASE       )
							a_		:	str									=   {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}

							a_		:	Optional[Any]									=   [input_ids, input_mask]
							a_		:	Tuple									=   model(__SCREAMING_SNAKE_CASE       )

							a_		:	int									=   model(__SCREAMING_SNAKE_CASE       )

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






			def       SCREAMING_SNAKE_CASE   (			self   :      Optional[Any]	,    __SCREAMING_SNAKE_CASE   :      Tuple	,    __SCREAMING_SNAKE_CASE   :      Any	,    __SCREAMING_SNAKE_CASE   :      Any	,    __SCREAMING_SNAKE_CASE   :      List[str]	,    __SCREAMING_SNAKE_CASE   :      Tuple	,    __SCREAMING_SNAKE_CASE   :      Tuple	,    __SCREAMING_SNAKE_CASE   :      Dict       )      ->      str:
							a_		:	List[Any]									=   TFConvBertForMaskedLM(config=__SCREAMING_SNAKE_CASE       )
							a_		:	Dict									=   {
							    '''input_ids''': input_ids,
							    '''attention_mask''': input_mask,
							    '''token_type_ids''': token_type_ids,
							}
							a_		:	str									=   model(__SCREAMING_SNAKE_CASE       )
							self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.seq_length, self.vocab_size)       )






			def       SCREAMING_SNAKE_CASE   (			self   :      Optional[int]	,    __SCREAMING_SNAKE_CASE   :      str	,    __SCREAMING_SNAKE_CASE   :      int	,    __SCREAMING_SNAKE_CASE   :      str	,    __SCREAMING_SNAKE_CASE   :      List[str]	,    __SCREAMING_SNAKE_CASE   :      Dict	,    __SCREAMING_SNAKE_CASE   :      Tuple	,    __SCREAMING_SNAKE_CASE   :      int       )      ->      Any:
							a_		:	Union[str, Any]									=   self.num_labels
							a_		:	List[str]									=   TFConvBertForSequenceClassification(config=__SCREAMING_SNAKE_CASE       )
							a_		:	Optional[Any]									=   {
							    '''input_ids''': input_ids,
							    '''attention_mask''': input_mask,
							    '''token_type_ids''': token_type_ids,
							}

							a_		:	Tuple									=   model(__SCREAMING_SNAKE_CASE       )
							self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.num_labels)       )






			def       SCREAMING_SNAKE_CASE   (			self   :      List[Any]	,    __SCREAMING_SNAKE_CASE   :      List[str]	,    __SCREAMING_SNAKE_CASE   :      Optional[Any]	,    __SCREAMING_SNAKE_CASE   :      str	,    __SCREAMING_SNAKE_CASE   :      str	,    __SCREAMING_SNAKE_CASE   :      Dict	,    __SCREAMING_SNAKE_CASE   :      Tuple	,    __SCREAMING_SNAKE_CASE   :      Tuple       )      ->      Optional[int]:
							a_		:	Optional[Any]									=   self.num_choices
							a_		:	int									=   TFConvBertForMultipleChoice(config=__SCREAMING_SNAKE_CASE       )
							a_		:	List[str]									=   tf.tile(tf.expand_dims(__SCREAMING_SNAKE_CASE	,    1       )	,    (1, self.num_choices, 1)       )
							a_		:	Tuple									=   tf.tile(tf.expand_dims(__SCREAMING_SNAKE_CASE	,    1       )	,    (1, self.num_choices, 1)       )
							a_		:	List[Any]									=   tf.tile(tf.expand_dims(__SCREAMING_SNAKE_CASE	,    1       )	,    (1, self.num_choices, 1)       )
							a_		:	Union[str, Any]									=   {
							    '''input_ids''': multiple_choice_inputs_ids,
							    '''attention_mask''': multiple_choice_input_mask,
							    '''token_type_ids''': multiple_choice_token_type_ids,
							}
							a_		:	Optional[int]									=   model(__SCREAMING_SNAKE_CASE       )
							self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.num_choices)       )






			def       SCREAMING_SNAKE_CASE   (			self   :      List[Any]	,    __SCREAMING_SNAKE_CASE   :      List[str]	,    __SCREAMING_SNAKE_CASE   :      Dict	,    __SCREAMING_SNAKE_CASE   :      Optional[Any]	,    __SCREAMING_SNAKE_CASE   :      Union[str, Any]	,    __SCREAMING_SNAKE_CASE   :      Union[str, Any]	,    __SCREAMING_SNAKE_CASE   :      List[Any]	,    __SCREAMING_SNAKE_CASE   :      Tuple       )      ->      str:
							a_		:	Optional[Any]									=   self.num_labels
							a_		:	Optional[int]									=   TFConvBertForTokenClassification(config=__SCREAMING_SNAKE_CASE       )
							a_		:	Tuple									=   {
							    '''input_ids''': input_ids,
							    '''attention_mask''': input_mask,
							    '''token_type_ids''': token_type_ids,
							}
							a_		:	Tuple									=   model(__SCREAMING_SNAKE_CASE       )
							self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.seq_length, self.num_labels)       )






			def       SCREAMING_SNAKE_CASE   (			self   :      List[str]	,    __SCREAMING_SNAKE_CASE   :      Optional[Any]	,    __SCREAMING_SNAKE_CASE   :      List[Any]	,    __SCREAMING_SNAKE_CASE   :      List[Any]	,    __SCREAMING_SNAKE_CASE   :      str	,    __SCREAMING_SNAKE_CASE   :      Optional[int]	,    __SCREAMING_SNAKE_CASE   :      Tuple	,    __SCREAMING_SNAKE_CASE   :      Union[str, Any]       )      ->      Tuple:
							a_		:	List[Any]									=   TFConvBertForQuestionAnswering(config=__SCREAMING_SNAKE_CASE       )
							a_		:	Optional[Any]									=   {
							    '''input_ids''': input_ids,
							    '''attention_mask''': input_mask,
							    '''token_type_ids''': token_type_ids,
							}

							a_		:	Dict									=   model(__SCREAMING_SNAKE_CASE       )
							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       SCREAMING_SNAKE_CASE   (			self   :      List[str]       )      ->      Any:
							a_		:	List[Any]									=   self.prepare_config_and_inputs()
							(
							    (
							    a_
							)					,      (
							    a_
							)					,      (
							    a_
							)					,      (
							    a_
							)					,      (
							    a_
							)					,      (
							    a_
							)					,      (
							    a_
							)					,      
							)		:	List[Any]									=   config_and_inputs
							a_		:	Any									=   {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
							return config, inputs_dict





@require_tf
class 						SCREAMING_SNAKE_CASE       (       SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_						, unittest.TestCase							):
			snake_case__	=					(
			    (
			        TFConvBertModel,
			        TFConvBertForMaskedLM,
			        TFConvBertForQuestionAnswering,
			        TFConvBertForSequenceClassification,
			        TFConvBertForTokenClassification,
			        TFConvBertForMultipleChoice,
			    )
			    if is_tf_available()
			    else ()
			)
			snake_case__	=					(
			    {
			        "feature-extraction": TFConvBertModel,
			        "fill-mask": TFConvBertForMaskedLM,
			        "question-answering": TFConvBertForQuestionAnswering,
			        "text-classification": TFConvBertForSequenceClassification,
			        "token-classification": TFConvBertForTokenClassification,
			        "zero-shot": TFConvBertForSequenceClassification,
			    }
			    if is_tf_available()
			    else {}
			)
			snake_case__	=					False
			snake_case__	=					False
			snake_case__	=					False






			def       SCREAMING_SNAKE_CASE   (			self   :      List[str]       )      ->      List[Any]:
							a_		:	Optional[int]									=   TFConvBertModelTester(self       )
							a_		:	Any									=   ConfigTester(self	,    config_class=__SCREAMING_SNAKE_CASE	,    hidden_size=37       )






			def       SCREAMING_SNAKE_CASE   (			self   :      str       )      ->      Optional[Any]:
							self.config_tester.run_common_tests()






			def       SCREAMING_SNAKE_CASE   (			self   :      Tuple       )      ->      str:
							a_		:	Any									=   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE       )






			def       SCREAMING_SNAKE_CASE   (			self   :      Optional[Any]       )      ->      List[str]:
							a_		:	str									=   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_lm(*__SCREAMING_SNAKE_CASE       )






			def       SCREAMING_SNAKE_CASE   (			self   :      Any       )      ->      str:
							a_		:	Dict									=   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_multiple_choice(*__SCREAMING_SNAKE_CASE       )






			def       SCREAMING_SNAKE_CASE   (			self   :      str       )      ->      Optional[Any]:
							a_		:	Optional[Any]									=   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_question_answering(*__SCREAMING_SNAKE_CASE       )






			def       SCREAMING_SNAKE_CASE   (			self   :      Any       )      ->      str:
							a_		:	List[str]									=   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_sequence_classification(*__SCREAMING_SNAKE_CASE       )






			def       SCREAMING_SNAKE_CASE   (			self   :      str       )      ->      Optional[int]:
							a_		:	Any									=   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_token_classification(*__SCREAMING_SNAKE_CASE       )






			@slow
			def       SCREAMING_SNAKE_CASE   (			self   :      Optional[int]       )      ->      Union[str, Any]:
							a_					,      a_		:	Optional[Any]									=   self.model_tester.prepare_config_and_inputs_for_common()
							a_		:	Any									=   True
							a_		:	Optional[int]									=   True

							if hasattr(__SCREAMING_SNAKE_CASE	,    '''use_cache'''       ):
											a_		:	Dict									=   True

							a_		:	Any									=   getattr(self.model_tester	,    '''encoder_seq_length'''	,    self.model_tester.seq_length       )
							a_		:	List[Any]									=   getattr(self.model_tester	,    '''key_length'''	,    __SCREAMING_SNAKE_CASE       )

							for model_class in self.all_model_classes:
											a_		:	str									=   self._prepare_for_class(__SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE       )
											a_		:	Optional[int]									=   model_class(__SCREAMING_SNAKE_CASE       )
											a_		:	Any									=   len(model(__SCREAMING_SNAKE_CASE       )       )

											with tempfile.TemporaryDirectory() as tmpdirname:
															model.save_pretrained(__SCREAMING_SNAKE_CASE	,    saved_model=__SCREAMING_SNAKE_CASE       )
															a_		:	Union[str, Any]									=   os.path.join(__SCREAMING_SNAKE_CASE	,    '''saved_model'''	,    '''1'''       )
															a_		:	Optional[int]									=   tf.keras.models.load_model(__SCREAMING_SNAKE_CASE       )
															a_		:	Any									=   model(__SCREAMING_SNAKE_CASE       )

															if self.is_encoder_decoder:
																			a_		:	Optional[int]									=   outputs['''encoder_hidden_states''']
																			a_		:	Dict									=   outputs['''encoder_attentions''']
															else:
																			a_		:	Union[str, Any]									=   outputs['''hidden_states''']
																			a_		:	Tuple									=   outputs['''attentions''']

															self.assertEqual(len(__SCREAMING_SNAKE_CASE       )	,    __SCREAMING_SNAKE_CASE       )

															a_		:	Union[str, Any]									=   getattr(
															    self.model_tester	,    '''expected_num_hidden_layers'''	,    self.model_tester.num_hidden_layers + 1       )

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

															self.assertEqual(len(__SCREAMING_SNAKE_CASE       )	,    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       SCREAMING_SNAKE_CASE   (			self   :      str       )      ->      Optional[int]:
							a_		:	Tuple									=   TFConvBertModel.from_pretrained('''YituTech/conv-bert-base'''       )
							self.assertIsNotNone(__SCREAMING_SNAKE_CASE       )







			def       SCREAMING_SNAKE_CASE   (			self   :      Any       )      ->      List[Any]:
							a_					,      a_		:	Union[str, Any]									=   self.model_tester.prepare_config_and_inputs_for_common()
							a_		:	Optional[Any]									=   True
							a_		:	Dict									=   getattr(self.model_tester	,    '''decoder_seq_length'''	,    self.model_tester.seq_length       )
							a_		:	List[str]									=   getattr(self.model_tester	,    '''encoder_seq_length'''	,    self.model_tester.seq_length       )
							a_		:	Dict									=   getattr(self.model_tester	,    '''key_length'''	,    __SCREAMING_SNAKE_CASE       )
							a_		:	Any									=   getattr(self.model_tester	,    '''key_length'''	,    __SCREAMING_SNAKE_CASE       )

							def check_decoder_attentions_output(__SCREAMING_SNAKE_CASE   :      List[str]       ):
											a_		:	int									=   len(__SCREAMING_SNAKE_CASE       )
											self.assertEqual(out_len % 2	,    0       )
											a_		:	Dict									=   outputs.decoder_attentions
											self.assertEqual(len(__SCREAMING_SNAKE_CASE       )	,    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(__SCREAMING_SNAKE_CASE   :      List[str]       ):
											a_		:	Optional[int]									=   [
											    t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions)
											]
											self.assertEqual(len(__SCREAMING_SNAKE_CASE       )	,    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:
											a_		:	Tuple									=   True
											a_		:	Tuple									=   False
											a_		:	Optional[Any]									=   model_class(__SCREAMING_SNAKE_CASE       )
											a_		:	List[Any]									=   model(self._prepare_for_class(__SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE       )       )
											a_		:	Union[str, Any]									=   len(__SCREAMING_SNAKE_CASE       )
											self.assertEqual(config.output_hidden_states	,    __SCREAMING_SNAKE_CASE       )
											check_encoder_attentions_output(__SCREAMING_SNAKE_CASE       )

											if self.is_encoder_decoder:
															a_		:	Any									=   model_class(__SCREAMING_SNAKE_CASE       )
															a_		:	List[Any]									=   model(self._prepare_for_class(__SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE       )       )
															self.assertEqual(config.output_hidden_states	,    __SCREAMING_SNAKE_CASE       )
															check_decoder_attentions_output(__SCREAMING_SNAKE_CASE       )

											# Check that output attentions can also be changed via the config
											del inputs_dict["output_attentions"]
											a_		:	Union[str, Any]									=   True
											a_		:	Union[str, Any]									=   model_class(__SCREAMING_SNAKE_CASE       )
											a_		:	int									=   model(self._prepare_for_class(__SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE       )       )
											self.assertEqual(config.output_hidden_states	,    __SCREAMING_SNAKE_CASE       )
											check_encoder_attentions_output(__SCREAMING_SNAKE_CASE       )

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

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





@require_tf
class 						SCREAMING_SNAKE_CASE       (       unittest.TestCase							):






			@slow
			def       SCREAMING_SNAKE_CASE   (			self   :      int       )      ->      Any:
							a_		:	int									=   TFConvBertModel.from_pretrained('''YituTech/conv-bert-base'''       )
							a_		:	List[Any]									=   tf.constant([[0, 1, 2, 3, 4, 5]]       )
							a_		:	Any									=   model(__SCREAMING_SNAKE_CASE       )[0]

							a_		:	str									=   [1, 6, 768]
							self.assertEqual(output.shape	,    __SCREAMING_SNAKE_CASE       )

							a_		:	Dict									=   tf.constant(
							    [
							        [
							            [-0.0347_5493, -0.468_6034, -0.3063_8832],
							            [0.2263_7248, -0.2698_8646, -0.742_3424],
							            [0.1032_4868, -0.4501_3508, -0.5828_0784],
							        ]
							    ]       )
							tf.debugging.assert_near(output[:, :3, :3]	,    __SCREAMING_SNAKE_CASE	,    atol=1e-4       )




