


import os
from argparse import ArgumentParser, Namespace

from ..data import SingleSentenceClassificationProcessor as Processor
from ..pipelines import TextClassificationPipeline
from ..utils import is_tf_available, is_torch_available, logging
from . import BaseTransformersCLICommand


if not is_tf_available() and not is_torch_available():
     raise RuntimeError("""At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training""")

# TF training parameters
UpperCamelCase								=	False
UpperCamelCase								=	False


def   _SCREAMING_SNAKE_CASE	( SCREAMING_SNAKE_CASE       ):
  return TrainCommand(SCREAMING_SNAKE_CASE       )







class   _lowerCamelCase (					A__			):




       """simple docstring"""



       @staticmethod
       def        _snake_case       (      _SCREAMING_SNAKE_CASE		)->Any:




         '''simple docstring'''





         A_      :				List[Any]		     =					parser.add_parser('''train'''				,       help='''CLI tool to train a model on a task.'''		)

         train_parser.add_argument(
             '''--train_data'''				,       type=_A				,       required=_A				,       help='''path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.'''				,       )
         train_parser.add_argument(
             '''--column_label'''				,       type=_A				,       default=0				,       help='''Column of the dataset csv file with example labels.'''		)
         train_parser.add_argument(
             '''--column_text'''				,       type=_A				,       default=1				,       help='''Column of the dataset csv file with example texts.'''		)
         train_parser.add_argument(
             '''--column_id'''				,       type=_A				,       default=2				,       help='''Column of the dataset csv file with example ids.'''		)
         train_parser.add_argument(
             '''--skip_first_row'''				,       action='''store_true'''				,       help='''Skip the first row of the csv file (headers).'''		)

         train_parser.add_argument('''--validation_data'''				,       type=_A				,       default=''''''				,       help='''path to validation dataset.'''		)
         train_parser.add_argument(
             '''--validation_split'''				,       type=_A				,       default=0.1				,       help='''if validation dataset is not provided, fraction of train dataset to use as validation dataset.'''				,       )

         train_parser.add_argument('''--output'''				,       type=_A				,       default='''./'''				,       help='''path to saved the trained model.'''		)

         train_parser.add_argument(
             '''--task'''				,       type=_A				,       default='''text_classification'''				,       help='''Task to train the model on.'''		)
         train_parser.add_argument(
             '''--model'''				,       type=_A				,       default='''bert-base-uncased'''				,       help='''Model\'s name or path to stored model.'''		)
         train_parser.add_argument('''--train_batch_size'''				,       type=_A				,       default=32				,       help='''Batch size for training.'''		)
         train_parser.add_argument('''--valid_batch_size'''				,       type=_A				,       default=64				,       help='''Batch size for validation.'''		)
         train_parser.add_argument('''--learning_rate'''				,       type=_A				,       default=3e-5				,       help='''Learning rate.'''		)
         train_parser.add_argument('''--adam_epsilon'''				,       type=_A				,       default=1e-08				,       help='''Epsilon for Adam optimizer.'''		)
         train_parser.set_defaults(func=_A		)



       def __init__(      self				,       _SCREAMING_SNAKE_CASE		)->Union[str, Any]:




         '''simple docstring'''





         A_      :				Optional[int]		     =					logging.get_logger('''transformers-cli/training'''		)

         A_      :				Any		     =					"tf" if is_tf_available() else "torch"

         os.makedirs(args.output				,       exist_ok=_A		)
         A_      :				Union[str, Any]		     =					args.output

         A_      :				Optional[int]		     =					args.column_label
         A_      :				Optional[int]		     =					args.column_text
         A_      :				int		     =					args.column_id

         self.logger.info(F'''Loading {args.task} pipeline for {args.model}'''		)
         if args.task == "text_classification":
           A_      :				str		     =					TextClassificationPipeline.from_pretrained(args.model		)
         elif args.task == "token_classification":
           raise NotImplementedError
         elif args.task == "question_answering":
           raise NotImplementedError

         self.logger.info(F'''Loading dataset from {args.train_data}'''		)
         A_      :				Dict		     =					Processor.create_from_csv(
             args.train_data				,       column_label=args.column_label				,       column_text=args.column_text				,       column_id=args.column_id				,       skip_first_row=args.skip_first_row				,       )
         A_      :				Tuple		     =					None
         if args.validation_data:
           self.logger.info(F'''Loading validation dataset from {args.validation_data}'''		)
           A_      :				Optional[Any]		     =					Processor.create_from_csv(
               args.validation_data				,       column_label=args.column_label				,       column_text=args.column_text				,       column_id=args.column_id				,       skip_first_row=args.skip_first_row				,       )

         A_      :				str		     =					args.validation_split
         A_      :				int		     =					args.train_batch_size
         A_      :				Union[str, Any]		     =					args.valid_batch_size
         A_      :				Any		     =					args.learning_rate
         A_      :				Union[str, Any]		     =					args.adam_epsilon



       def        _snake_case       (      self		)->str:




         '''simple docstring'''





         if self.framework == "tf":
           return self.run_tf()
         return self.run_torch()



       def        _snake_case       (      self		)->Tuple:




         '''simple docstring'''





         raise NotImplementedError







       def        _snake_case       (      self		)->Optional[int]:




         '''simple docstring'''





         self.pipeline.fit(
             self.train_dataset				,       validation_data=self.valid_dataset				,       validation_split=self.validation_split				,       learning_rate=self.learning_rate				,       adam_epsilon=self.adam_epsilon				,       train_batch_size=self.train_batch_size				,       valid_batch_size=self.valid_batch_size				,       )

         # Save trained pipeline
         self.pipeline.save_pretrained(self.output		)





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







							"""simple docstring"""






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

					def 				__UpperCamelCase   (    self      :       str    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[str]				      =    ids_tensor([self.batch_size, self.seq_length],self.vocab_size    )

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

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

							SCREAMING_SNAKE_CASE_  :		Dict				      =    None
							SCREAMING_SNAKE_CASE_  :		Dict				      =    None
							SCREAMING_SNAKE_CASE_  :		str				      =    None
							if self.use_labels:
									SCREAMING_SNAKE_CASE_  :		List[str]				      =    ids_tensor([self.batch_size],self.type_sequence_label_size    )
									SCREAMING_SNAKE_CASE_  :		Dict				      =    ids_tensor([self.batch_size, self.seq_length],self.num_labels    )
									SCREAMING_SNAKE_CASE_  :		List[str]				      =    ids_tensor([self.batch_size],self.num_choices    )

							SCREAMING_SNAKE_CASE_  :		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      :       Optional[int],_A      :       List[Any],_A      :       int,_A      :       Tuple,_A      :       Optional[int],_A      :       Union[str, Any],_A      :       Union[str, Any],_A      :       List[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    TFConvBertModel(config=_A    )
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}

							SCREAMING_SNAKE_CASE_  :		str				      =    [input_ids, input_mask]
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    model(_A    )

							SCREAMING_SNAKE_CASE_  :		Dict				      =    model(_A    )

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

					def 				__UpperCamelCase   (    self      :       Dict,_A      :       Dict,_A      :       int,_A      :       Union[str, Any],_A      :       List[Any],_A      :       int,_A      :       str,_A      :       int    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Dict				      =    TFConvBertForMaskedLM(config=_A    )
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    {
							    "input_ids": input_ids,
							    "attention_mask": input_mask,
							    "token_type_ids": token_type_ids,
							}
							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    model(_A    )
							self.parent.assertEqual(result.logits.shape,(self.batch_size, self.seq_length, self.vocab_size)    )

					def 				__UpperCamelCase   (    self      :       Any,_A      :       Optional[int],_A      :       List[Any],_A      :       Union[str, Any],_A      :       List[Any],_A      :       Union[str, Any],_A      :       Optional[int],_A      :       Dict    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    self.num_labels
							SCREAMING_SNAKE_CASE_  :		Any				      =    TFConvBertForSequenceClassification(config=_A    )
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    {
							    "input_ids": input_ids,
							    "attention_mask": input_mask,
							    "token_type_ids": token_type_ids,
							}

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

					def 				__UpperCamelCase   (    self      :       int,_A      :       int,_A      :       Dict,_A      :       List[str],_A      :       Tuple,_A      :       Dict,_A      :       Optional[int],_A      :       int    ):







							"""simple docstring"""






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

					def 				__UpperCamelCase   (    self      :       List[Any],_A      :       Union[str, Any],_A      :       int,_A      :       Optional[int],_A      :       str,_A      :       str,_A      :       Tuple,_A      :       str    ):







							"""simple docstring"""






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

					def 				__UpperCamelCase   (    self      :       List[Any],_A      :       int,_A      :       List[str],_A      :       List[Any],_A      :       Any,_A      :       Optional[int],_A      :       List[str],_A      :       Optional[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    TFConvBertForQuestionAnswering(config=_A    )
							SCREAMING_SNAKE_CASE_  :		Dict				      =    {
							    "input_ids": input_ids,
							    "attention_mask": input_mask,
							    "token_type_ids": token_type_ids,
							}

							SCREAMING_SNAKE_CASE_  :		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      :       Tuple    ):







							"""simple docstring"""






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







@require_tf
class 		a__						(					A__    ,		A__    ,		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 				__UpperCamelCase   (    self      :       List[str]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		str				      =    TFConvBertModelTester(self    )
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    ConfigTester(self,config_class=_A,hidden_size=37    )

					def 				__UpperCamelCase   (    self      :       Optional[int]    ):







							"""simple docstring"""






							self.config_tester.run_common_tests()

					def 				__UpperCamelCase   (    self      :       Optional[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_A    )

					def 				__UpperCamelCase   (    self      :       Optional[int]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		int				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_lm(*_A    )

					def 				__UpperCamelCase   (    self      :       Optional[int]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Dict				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_multiple_choice(*_A    )

					def 				__UpperCamelCase   (    self      :       str    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[str]				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_question_answering(*_A    )

					def 				__UpperCamelCase   (    self      :       List[str]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_sequence_classification(*_A    )

					def 				__UpperCamelCase   (    self      :       Optional[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[str]				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_token_classification(*_A    )

					@slow
					def 				__UpperCamelCase   (    self      :       Optional[int]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    self.model_tester.prepare_config_and_inputs_for_common()
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    True
							SCREAMING_SNAKE_CASE_  :		Any				      =    True

							if hasattr(_A,"use_cache"    ):
									SCREAMING_SNAKE_CASE_  :		List[Any]				      =    True

							SCREAMING_SNAKE_CASE_  :		int				      =    getattr(self.model_tester,"encoder_seq_length",self.model_tester.seq_length    )
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    getattr(self.model_tester,"key_length",_A    )

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

									with tempfile.TemporaryDirectory() as tmpdirname:
											model.save_pretrained(_A,saved_model=_A    )
											SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    os.path.join(_A,"saved_model","1"    )
											SCREAMING_SNAKE_CASE_  :		Tuple				      =    tf.keras.models.load_model(_A    )
											SCREAMING_SNAKE_CASE_  :		str				      =    model(_A    )

											if self.is_encoder_decoder:
													SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    outputs["encoder_hidden_states"]
													SCREAMING_SNAKE_CASE_  :		str				      =    outputs["encoder_attentions"]
											else:
													SCREAMING_SNAKE_CASE_  :		Any				      =    outputs["hidden_states"]
													SCREAMING_SNAKE_CASE_  :		List[str]				      =    outputs["attentions"]

											self.assertEqual(len(_A    ),_A    )

											SCREAMING_SNAKE_CASE_  :		Any				      =    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      :       List[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		str				      =    TFConvBertModel.from_pretrained("YituTech/conv-bert-base"    )
							self.assertIsNotNone(_A    )






					def 				__UpperCamelCase   (    self      :       Tuple    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		Any				      =    self.model_tester.prepare_config_and_inputs_for_common()
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    True
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    getattr(self.model_tester,"decoder_seq_length",self.model_tester.seq_length    )
							SCREAMING_SNAKE_CASE_  :		Any				      =    getattr(self.model_tester,"encoder_seq_length",self.model_tester.seq_length    )
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    getattr(self.model_tester,"key_length",_A    )
							SCREAMING_SNAKE_CASE_  :		int				      =    getattr(self.model_tester,"key_length",_A    )

							def check_decoder_attentions_output(_A      :       Dict    ):
									SCREAMING_SNAKE_CASE_  :		int				      =    len(_A    )
									self.assertEqual(out_len % 2,0    )
									SCREAMING_SNAKE_CASE_  :		Tuple				      =    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      :       Tuple    ):
									SCREAMING_SNAKE_CASE_  :		int				      =    [
									    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:
									SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    True
									SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    False
									SCREAMING_SNAKE_CASE_  :		Tuple				      =    model_class(_A    )
									SCREAMING_SNAKE_CASE_  :		Any				      =    model(self._prepare_for_class(_A,_A    )    )
									SCREAMING_SNAKE_CASE_  :		Tuple				      =    len(_A    )
									self.assertEqual(config.output_hidden_states,_A    )
									check_encoder_attentions_output(_A    )

									if self.is_encoder_decoder:
											SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    model_class(_A    )
											SCREAMING_SNAKE_CASE_  :		int				      =    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"]
									SCREAMING_SNAKE_CASE_  :		str				      =    True
									SCREAMING_SNAKE_CASE_  :		int				      =    model_class(_A    )
									SCREAMING_SNAKE_CASE_  :		List[str]				      =    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
									SCREAMING_SNAKE_CASE_  :		str				      =    True
									SCREAMING_SNAKE_CASE_  :		int				      =    True
									SCREAMING_SNAKE_CASE_  :		Dict				      =    model_class(_A    )
									SCREAMING_SNAKE_CASE_  :		str				      =    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      :       Union[str, Any]    ):







							"""simple docstring"""






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

							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    [1, 6, 768]
							self.assertEqual(output.shape,_A    )

							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    tf.constant(
							    [
							        [
							            [-0.03475493, -0.4686034, -0.30638832],
							            [0.22637248, -0.26988646, -0.7423424],
							            [0.10324868, -0.45013508, -0.58280784],
							        ]
							    ]    )
							tf.debugging.assert_near(output[:, :3, :3],_A,atol=1E-4    )
