






'''simple docstring'''







import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import torch
from datasets import load_dataset
from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor
from torchvision.transforms.functional import InterpolationMode

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    ViTImageProcessor,
    ViTMAEConfig,
    ViTMAEForPreTraining,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
_A			:    Optional[Any]					  =logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('''4.31.0''')

require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt''')

@dataclass
class _lowercase			:
							a          = field(
							    default="""cifar10"""       ,   metadata={"""help""": """Name of a dataset from the datasets package"""}	)
							a          = field(
							    default=_lowercase       ,   metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}	)
							a          = field(
							    default=_lowercase       ,   metadata={"""help""": """The column name of the images in the files."""}	)
							a          = field(default=_lowercase       ,   metadata={"""help""": """A folder containing the training data."""}	)
							a          = field(default=_lowercase       ,   metadata={"""help""": """A folder containing the validation data."""}	)
							a          = field(
							    default=0.15       ,   metadata={"""help""": """Percent to split off of train for validation."""}	)
							a          = field(
							    default=_lowercase       ,   metadata={
							        """help""": (
							            """For debugging purposes or quicker training, truncate the number of training examples to this """
							            """value if set."""
							        )
							    }       ,   )
							a          = field(
							    default=_lowercase       ,   metadata={
							        """help""": (
							            """For debugging purposes or quicker training, truncate the number of evaluation examples to this """
							            """value if set."""
							        )
							    }       ,   )




							def 	lowerCamelCase_       (							self:       Optional[Any]  ):
														lowerCamelCase__      :			Union[str, Any] 						= {}
														if self.train_dir is not None:
																					lowerCamelCase__      :			Tuple 						= self.train_dir
														if self.validation_dir is not None:
																					lowerCamelCase__      :			int 						= self.validation_dir
														lowerCamelCase__      :			Union[str, Any] 						= data_files if data_files else None



@dataclass
class _lowercase			:
							a          = field(
							    default=_lowercase       ,   metadata={
							        """help""": (
							            """The model checkpoint for weights initialization.Don't set if you want to train a model from scratch."""
							        )
							    }       ,   )
							a          = field(
							    default=_lowercase       ,   metadata={"""help""": """Pretrained config name or path if not the same as model_name_or_path"""}	)
							a          = field(
							    default=_lowercase       ,   metadata={
							        """help""": (
							            """Override some existing default config settings when a model is trained from scratch. Example: """
							            """n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"""
							        )
							    }       ,   )
							a          = field(
							    default=_lowercase       ,   metadata={"""help""": """Where do you want to store the pretrained models downloaded from s3"""}	)
							a          = field(
							    default="""main"""       ,   metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""}       ,   )
							a          = field(default=_lowercase       ,   metadata={"""help""": """Name or path of preprocessor config."""}	)
							a          = field(
							    default=_lowercase       ,   metadata={
							        """help""": (
							            """Will use the token generated when running `huggingface-cli login` (necessary to use this script """
							            """with private models)."""
							        )
							    }       ,   )
							a          = field(
							    default=0.75       ,   metadata={"""help""": """The ratio of the number of masked tokens in the input sequence."""}	)
							a          = field(
							    default=_lowercase       ,   metadata={"""help""": """Whether or not to train with normalized pixel values as target."""}	)



@dataclass
class _lowercase			(       _lowercase	):
							a          = field(
							    default=1e-3       ,   metadata={"""help""": """Base learning rate: absolute_lr = base_lr * total_batch_size / 256."""}	)





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> Dict:
							lowerCamelCase__      :			Optional[Any] 						= torch.stack([example["""pixel_values"""] for example in examples]   )
							return {"pixel_values": pixel_values}





def 				SCREAMING_SNAKE_CASE_ ()   -> Union[str, Any]:
							# See all possible arguments in src/transformers/training_args.py
							# or by passing the --help flag to this script.
							# We now keep distinct sets of args, for a cleaner separation of concerns.

							lowerCamelCase__      :			str 						= HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments)   )
							if len(sys.argv   ) == 2 and sys.argv[1].endswith(""".json"""   ):
														# If we pass only one argument to the script and it's the path to a json file,
														# let's parse it to get our arguments.
														lowerCamelCase__						,	lowerCamelCase__						,	lowerCamelCase__      :			List[Any] 						= parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]   )   )
							else:
														lowerCamelCase__						,	lowerCamelCase__						,	lowerCamelCase__      :			Union[str, Any] 						= parser.parse_args_into_dataclasses()

							# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
							# information sent is the one passed as arguments along with your Python/PyTorch versions.
							send_example_telemetry("""run_mae"""       ,    UpperCamelCase       ,    UpperCamelCase   )

							# Setup logging
							logging.basicConfig(
							    format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""       ,    datefmt="""%m/%d/%Y %H:%M:%S"""       ,    handlers=[logging.StreamHandler(sys.stdout   )]       ,    )

							if training_args.should_log:
														# The default of training_args.log_level is passive, so we set log level at info here to have that default.
														transformers.utils.logging.set_verbosity_info()

							lowerCamelCase__      :			Any 						= training_args.get_process_log_level()
							logger.setLevel(UpperCamelCase   )
							transformers.utils.logging.set_verbosity(UpperCamelCase   )
							transformers.utils.logging.enable_default_handler()
							transformers.utils.logging.enable_explicit_format()

							# Log on each process the small summary:
							logger.warning(
							    f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
							    + f'''distributed training: {bool(training_args.local_rank != -1   )}, 16-bits training: {training_args.fpaa}'''   )
							logger.info(f'''Training/evaluation parameters {training_args}'''   )

							# Detecting last checkpoint.
							lowerCamelCase__      :			List[str] 						= None
							if os.path.isdir(training_args.output_dir   ) and training_args.do_train and not training_args.overwrite_output_dir:
														lowerCamelCase__      :			Dict 						= get_last_checkpoint(training_args.output_dir   )
														if last_checkpoint is None and len(os.listdir(training_args.output_dir   )   ) > 0:
																					raise ValueError(
																					    f'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
																					    """Use --overwrite_output_dir to overcome."""   )
														elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
																					logger.info(
																					    f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
																					    """the `--output_dir` or add `--overwrite_output_dir` to train from scratch."""   )

    # Initialize our dataset.
							lowerCamelCase__      :			Dict 						= load_dataset(
							    data_args.dataset_name       ,    data_args.dataset_config_name       ,    data_files=data_args.data_files       ,    cache_dir=model_args.cache_dir       ,    use_auth_token=True if model_args.use_auth_token else None       ,    )

							# If we don't have a validation split, split off a percentage of train as validation.
							lowerCamelCase__      :			List[Any] 						= None if """validation""" in ds.keys() else data_args.train_val_split
							if isinstance(data_args.train_val_split       ,    UpperCamelCase   ) and data_args.train_val_split > 0.0:
														lowerCamelCase__      :			Dict 						= ds["""train"""].train_test_split(data_args.train_val_split   )
														lowerCamelCase__      :			Optional[Any] 						= split["""train"""]
														lowerCamelCase__      :			List[str] 						= split["""test"""]

							# Load pretrained model and image processor
							#
							# Distributed training:
							# The .from_pretrained methods guarantee that only one local process can concurrently
							# download model & vocab.
							lowerCamelCase__      :			Union[str, Any] 						= {
							    """cache_dir""": model_args.cache_dir,
							    """revision""": model_args.model_revision,
							    """use_auth_token""": True if model_args.use_auth_token else None,
							}
							if model_args.config_name:
														lowerCamelCase__      :			Tuple 						= ViTMAEConfig.from_pretrained(model_args.config_name       ,    **UpperCamelCase   )
							elif model_args.model_name_or_path:
														lowerCamelCase__      :			str 						= ViTMAEConfig.from_pretrained(model_args.model_name_or_path       ,    **UpperCamelCase   )
							else:
														lowerCamelCase__      :			Optional[int] 						= ViTMAEConfig()
														logger.warning("""You are instantiating a new config instance from scratch."""   )
														if model_args.config_overrides is not None:
																					logger.info(f'''Overriding config: {model_args.config_overrides}'''   )
																					config.update_from_string(model_args.config_overrides   )
																					logger.info(f'''New config: {config}'''   )

    # adapt config
							config.update(
							    {
							        """mask_ratio""": model_args.mask_ratio,
							        """norm_pix_loss""": model_args.norm_pix_loss,
							    }   )

							# create image processor
							if model_args.image_processor_name:
														lowerCamelCase__      :			Any 						= ViTImageProcessor.from_pretrained(model_args.image_processor_name       ,    **UpperCamelCase   )
							elif model_args.model_name_or_path:
														lowerCamelCase__      :			List[str] 						= ViTImageProcessor.from_pretrained(model_args.model_name_or_path       ,    **UpperCamelCase   )
							else:
														lowerCamelCase__      :			str 						= ViTImageProcessor()

							# create model
							if model_args.model_name_or_path:
														lowerCamelCase__      :			Any 						= ViTMAEForPreTraining.from_pretrained(
														    model_args.model_name_or_path       ,    from_tf=bool(""".ckpt""" in model_args.model_name_or_path   )       ,    config=UpperCamelCase       ,    cache_dir=model_args.cache_dir       ,    revision=model_args.model_revision       ,    use_auth_token=True if model_args.use_auth_token else None       ,    )
							else:
														logger.info("""Training new model from scratch"""   )
														lowerCamelCase__      :			Tuple 						= ViTMAEForPreTraining(UpperCamelCase   )

							if training_args.do_train:
														lowerCamelCase__      :			Any 						= ds["""train"""].column_names
							else:
														lowerCamelCase__      :			Dict 						= ds["""validation"""].column_names

							if data_args.image_column_name is not None:
														lowerCamelCase__      :			int 						= data_args.image_column_name
							elif "image" in column_names:
														lowerCamelCase__      :			List[Any] 						= """image"""
							elif "img" in column_names:
														lowerCamelCase__      :			str 						= """img"""
							else:
														lowerCamelCase__      :			int 						= column_names[0]

							# transformations as done in original MAE paper
							# source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py
							if "shortest_edge" in image_processor.size:
														lowerCamelCase__      :			int 						= image_processor.size["""shortest_edge"""]
							else:
														lowerCamelCase__      :			List[str] 						= (image_processor.size["""height"""], image_processor.size["""width"""])
							lowerCamelCase__      :			Tuple 						= Compose(
							    [
							        Lambda(lambda UpperCamelCase   : img.convert("""RGB"""   ) if img.mode != "RGB" else img   ),
							        RandomResizedCrop(UpperCamelCase       ,    scale=(0.2, 1.0)       ,    interpolation=InterpolationMode.BICUBIC   ),
							        RandomHorizontalFlip(),
							        ToTensor(),
							        Normalize(mean=image_processor.image_mean       ,    std=image_processor.image_std   ),
							    ]   )

							def preprocess_images(UpperCamelCase   ):
														lowerCamelCase__      :			Optional[int] 						= [transforms(UpperCamelCase   ) for image in examples[image_column_name]]
														return examples

							if training_args.do_train:
														if "train" not in ds:
																					raise ValueError("""--do_train requires a train dataset"""   )
														if data_args.max_train_samples is not None:
																					lowerCamelCase__      :			Tuple 						= ds["""train"""].shuffle(seed=training_args.seed   ).select(range(data_args.max_train_samples   )   )
														# Set the training transforms
														ds["train"].set_transform(UpperCamelCase   )

							if training_args.do_eval:
														if "validation" not in ds:
																					raise ValueError("""--do_eval requires a validation dataset"""   )
														if data_args.max_eval_samples is not None:
																					lowerCamelCase__      :			Optional[int] 						= (
																					    ds["""validation"""].shuffle(seed=training_args.seed   ).select(range(data_args.max_eval_samples   )   )
																					)
														# Set the validation transforms
														ds["validation"].set_transform(UpperCamelCase   )

							# Compute absolute learning rate
							lowerCamelCase__      :			str 						= (
							    training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size
							)
							if training_args.base_learning_rate is not None:
														lowerCamelCase__      :			List[Any] 						= training_args.base_learning_rate * total_train_batch_size / 256

							# Initialize our trainer
							lowerCamelCase__      :			List[Any] 						= Trainer(
							    model=UpperCamelCase       ,    args=UpperCamelCase       ,    train_dataset=ds["""train"""] if training_args.do_train else None       ,    eval_dataset=ds["""validation"""] if training_args.do_eval else None       ,    tokenizer=UpperCamelCase       ,    data_collator=UpperCamelCase       ,    )

							# Training
							if training_args.do_train:
														lowerCamelCase__      :			Optional[int] 						= None
														if training_args.resume_from_checkpoint is not None:
																					lowerCamelCase__      :			Union[str, Any] 						= training_args.resume_from_checkpoint
														elif last_checkpoint is not None:
																					lowerCamelCase__      :			Tuple 						= last_checkpoint
														lowerCamelCase__      :			Tuple 						= trainer.train(resume_from_checkpoint=UpperCamelCase   )
														trainer.save_model()
														trainer.log_metrics("""train"""       ,    train_result.metrics   )
														trainer.save_metrics("""train"""       ,    train_result.metrics   )
														trainer.save_state()

							# Evaluation
							if training_args.do_eval:
														lowerCamelCase__      :			Tuple 						= trainer.evaluate()
														trainer.log_metrics("""eval"""       ,    UpperCamelCase   )
														trainer.save_metrics("""eval"""       ,    UpperCamelCase   )

							# Write model card and (optionally) push to hub
							lowerCamelCase__      :			Tuple 						= {
							    """tasks""": """masked-auto-encoding""",
							    """dataset""": data_args.dataset_name,
							    """tags""": ["""masked-auto-encoding"""],
							}
							if training_args.push_to_hub:
														trainer.push_to_hub(**UpperCamelCase   )
							else:
														trainer.create_model_card(**UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> List[Any]:
							# For xla_spawn (TPUs)
							main()


if __name__ == "__main__":
			main()









'''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 _lowercase			:




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




							def 	lowerCamelCase_       (							self:       List[Any]  ):
														lowerCamelCase__      :			Tuple 						= ids_tensor([self.batch_size, self.seq_length]    ,							self.vocab_size  )

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

														lowerCamelCase__      :			List[str] 						= None
														if self.use_token_type_ids:
																					lowerCamelCase__      :			Optional[Any] 						= ids_tensor([self.batch_size, self.seq_length]    ,							self.type_vocab_size  )

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

														lowerCamelCase__      :			List[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=UpperCamelCase__    ,							)

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




							def 	lowerCamelCase_       (							self:       Optional[int]    ,							UpperCamelCase__:       Dict    ,							UpperCamelCase__:       List[str]    ,							UpperCamelCase__:       Any    ,							UpperCamelCase__:       Any    ,							UpperCamelCase__:       Any    ,							UpperCamelCase__:       str    ,							UpperCamelCase__:       Any  ):
														lowerCamelCase__      :			List[Any] 						= TFConvBertModel(config=UpperCamelCase__  )
														lowerCamelCase__      :			str 						= {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}

														lowerCamelCase__      :			List[str] 						= [input_ids, input_mask]
														lowerCamelCase__      :			Optional[int] 						= model(UpperCamelCase__  )

														lowerCamelCase__      :			Optional[Any] 						= model(UpperCamelCase__  )

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




							def 	lowerCamelCase_       (							self:       Any    ,							UpperCamelCase__:       Tuple    ,							UpperCamelCase__:       List[Any]    ,							UpperCamelCase__:       List[Any]    ,							UpperCamelCase__:       List[str]    ,							UpperCamelCase__:       List[Any]    ,							UpperCamelCase__:       Union[str, Any]    ,							UpperCamelCase__:       Tuple  ):
														lowerCamelCase__      :			int 						= TFConvBertForMaskedLM(config=UpperCamelCase__  )
														lowerCamelCase__      :			Tuple 						= {
														    """input_ids""": input_ids,
														    """attention_mask""": input_mask,
														    """token_type_ids""": token_type_ids,
														}
														lowerCamelCase__      :			int 						= model(UpperCamelCase__  )
														self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, self.seq_length, self.vocab_size)  )




							def 	lowerCamelCase_       (							self:       str    ,							UpperCamelCase__:       List[str]    ,							UpperCamelCase__:       Optional[int]    ,							UpperCamelCase__:       List[Any]    ,							UpperCamelCase__:       Optional[int]    ,							UpperCamelCase__:       Any    ,							UpperCamelCase__:       Any    ,							UpperCamelCase__:       Union[str, Any]  ):
														lowerCamelCase__      :			int 						= self.num_labels
														lowerCamelCase__      :			Dict 						= TFConvBertForSequenceClassification(config=UpperCamelCase__  )
														lowerCamelCase__      :			Dict 						= {
														    """input_ids""": input_ids,
														    """attention_mask""": input_mask,
														    """token_type_ids""": token_type_ids,
														}

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




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




							def 	lowerCamelCase_       (							self:       str    ,							UpperCamelCase__:       Any    ,							UpperCamelCase__:       Tuple    ,							UpperCamelCase__:       Optional[int]    ,							UpperCamelCase__:       Any    ,							UpperCamelCase__:       Optional[int]    ,							UpperCamelCase__:       str    ,							UpperCamelCase__:       int  ):
														lowerCamelCase__      :			List[Any] 						= self.num_labels
														lowerCamelCase__      :			List[str] 						= TFConvBertForTokenClassification(config=UpperCamelCase__  )
														lowerCamelCase__      :			Optional[Any] 						= {
														    """input_ids""": input_ids,
														    """attention_mask""": input_mask,
														    """token_type_ids""": token_type_ids,
														}
														lowerCamelCase__      :			Tuple 						= model(UpperCamelCase__  )
														self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, self.seq_length, self.num_labels)  )




							def 	lowerCamelCase_       (							self:       Any    ,							UpperCamelCase__:       List[Any]    ,							UpperCamelCase__:       str    ,							UpperCamelCase__:       Tuple    ,							UpperCamelCase__:       Optional[int]    ,							UpperCamelCase__:       Optional[Any]    ,							UpperCamelCase__:       List[str]    ,							UpperCamelCase__:       Optional[Any]  ):
														lowerCamelCase__      :			Optional[int] 						= TFConvBertForQuestionAnswering(config=UpperCamelCase__  )
														lowerCamelCase__      :			int 						= {
														    """input_ids""": input_ids,
														    """attention_mask""": input_mask,
														    """token_type_ids""": token_type_ids,
														}

														lowerCamelCase__      :			Optional[int] 						= model(UpperCamelCase__  )
														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 	lowerCamelCase_       (							self:       Optional[Any]  ):
														lowerCamelCase__      :			str 						= self.prepare_config_and_inputs()
														(
														    (
														    lowerCamelCase__
														)						,	(
														    lowerCamelCase__
														)						,	(
														    lowerCamelCase__
														)						,	(
														    lowerCamelCase__
														)						,	(
														    lowerCamelCase__
														)						,	(
														    lowerCamelCase__
														)						,	(
														    lowerCamelCase__
														)						,	
														)      :			str 						= config_and_inputs
														lowerCamelCase__      :			Optional[Any] 						= {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
														return config, inputs_dict



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




							def 	lowerCamelCase_       (							self:       str  ):
														lowerCamelCase__      :			Dict 						= TFConvBertModelTester(self  )
														lowerCamelCase__      :			Dict 						= ConfigTester(self    ,							config_class=UpperCamelCase__    ,							hidden_size=37  )




							def 	lowerCamelCase_       (							self:       List[str]  ):
														self.config_tester.run_common_tests()




							def 	lowerCamelCase_       (							self:       Union[str, Any]  ):
														lowerCamelCase__      :			List[str] 						= self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*UpperCamelCase__  )




							def 	lowerCamelCase_       (							self:       Any  ):
														lowerCamelCase__      :			Dict 						= self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__  )




							def 	lowerCamelCase_       (							self:       Tuple  ):
														lowerCamelCase__      :			int 						= self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase__  )




							def 	lowerCamelCase_       (							self:       Union[str, Any]  ):
														lowerCamelCase__      :			int 						= self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__  )




							def 	lowerCamelCase_       (							self:       Any  ):
														lowerCamelCase__      :			Union[str, Any] 						= self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__  )




							def 	lowerCamelCase_       (							self:       str  ):
														lowerCamelCase__      :			Tuple 						= self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__  )




							@slow
							def 	lowerCamelCase_       (							self:       Optional[Any]  ):
														lowerCamelCase__						,	lowerCamelCase__      :			List[str] 						= self.model_tester.prepare_config_and_inputs_for_common()
														lowerCamelCase__      :			Dict 						= True
														lowerCamelCase__      :			Tuple 						= True

														if hasattr(UpperCamelCase__    ,							"""use_cache"""  ):
																					lowerCamelCase__      :			Union[str, Any] 						= True

														lowerCamelCase__      :			List[str] 						= getattr(self.model_tester    ,							"""encoder_seq_length"""    ,							self.model_tester.seq_length  )
														lowerCamelCase__      :			Tuple 						= getattr(self.model_tester    ,							"""key_length"""    ,							UpperCamelCase__  )

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

																					with tempfile.TemporaryDirectory() as tmpdirname:
																												model.save_pretrained(UpperCamelCase__    ,							saved_model=UpperCamelCase__  )
																												lowerCamelCase__      :			int 						= os.path.join(UpperCamelCase__    ,							"""saved_model"""    ,							"""1"""  )
																												lowerCamelCase__      :			List[Any] 						= tf.keras.models.load_model(UpperCamelCase__  )
																												lowerCamelCase__      :			Any 						= model(UpperCamelCase__  )

																												if self.is_encoder_decoder:
																																			lowerCamelCase__      :			Dict 						= outputs["""encoder_hidden_states"""]
																																			lowerCamelCase__      :			Any 						= outputs["""encoder_attentions"""]
																												else:
																																			lowerCamelCase__      :			int 						= outputs["""hidden_states"""]
																																			lowerCamelCase__      :			Optional[int] 						= outputs["""attentions"""]

																												self.assertEqual(len(UpperCamelCase__  )    ,							UpperCamelCase__  )

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

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

																												self.assertEqual(len(UpperCamelCase__  )    ,							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 	lowerCamelCase_       (							self:       int  ):
														lowerCamelCase__      :			Union[str, Any] 						= TFConvBertModel.from_pretrained("""YituTech/conv-bert-base"""  )
														self.assertIsNotNone(UpperCamelCase__  )




							def 	lowerCamelCase_       (							self:       List[str]  ):
														lowerCamelCase__						,	lowerCamelCase__      :			Any 						= self.model_tester.prepare_config_and_inputs_for_common()
														lowerCamelCase__      :			Union[str, Any] 						= True
														lowerCamelCase__      :			int 						= getattr(self.model_tester    ,							"""decoder_seq_length"""    ,							self.model_tester.seq_length  )
														lowerCamelCase__      :			Any 						= getattr(self.model_tester    ,							"""encoder_seq_length"""    ,							self.model_tester.seq_length  )
														lowerCamelCase__      :			Optional[int] 						= getattr(self.model_tester    ,							"""key_length"""    ,							UpperCamelCase__  )
														lowerCamelCase__      :			List[Any] 						= getattr(self.model_tester    ,							"""key_length"""    ,							UpperCamelCase__  )

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

																					if self.is_encoder_decoder:
																												lowerCamelCase__      :			str 						= model_class(UpperCamelCase__  )
																												lowerCamelCase__      :			Tuple 						= model(self._prepare_for_class(UpperCamelCase__    ,							UpperCamelCase__  )  )
																												self.assertEqual(config.output_hidden_states    ,							UpperCamelCase__  )
																												check_decoder_attentions_output(UpperCamelCase__  )

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

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

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



@require_tf
class _lowercase			(       unittest.TestCase	):




							@slow
							def 	lowerCamelCase_       (							self:       List[str]  ):
														lowerCamelCase__      :			Dict 						= TFConvBertModel.from_pretrained("""YituTech/conv-bert-base"""  )
														lowerCamelCase__      :			Optional[Any] 						= tf.constant([[0, 1, 2, 3, 4, 5]]  )
														lowerCamelCase__      :			Optional[Any] 						= model(UpperCamelCase__  )[0]

														lowerCamelCase__      :			Dict 						= [1, 6, 768]
														self.assertEqual(output.shape    ,							UpperCamelCase__  )

														lowerCamelCase__      :			Dict 						= tf.constant(
														    [
														        [
														            [-0.03_475_493, -0.4_686_034, -0.30_638_832],
														            [0.22_637_248, -0.26_988_646, -0.7_423_424],
														            [0.10_324_868, -0.45_013_508, -0.58_280_784],
														        ]
														    ]  )
														tf.debugging.assert_near(output[:, :3, :3]    ,							UpperCamelCase__    ,							atol=1e-4  )

