





# XXX: we want transformers master here - in the absense of conftest manipulating sys.path:
# hack it in for now:
import sys
from pathlib import Path


UpperCAmelCase_     							= Path(__file__).resolve().parents[3] / 'src'
sys.path.insert(1, str(git_repo_path))

import dataclasses  # noqa
import io  # noqa
import itertools  # noqa
import json  # noqa
import os  # noqa
import unittest  # noqa
from copy import deepcopy  # noqa

from parameterized import parameterized  # noqa
from transformers import TrainingArguments, is_torch_available  # noqa
from transformers.deepspeed import is_deepspeed_available  # noqa
from transformers.file_utils import WEIGHTS_NAME  # noqa
from transformers.testing_utils import (  # noqa
    CaptureLogger,
    ExtendSysPath,
    TestCasePlus,
    execute_subprocess_async,
    get_gpu_count,
    mockenv_context,
    require_deepspeed,
    require_torch_gpu,
    require_torch_multi_gpu,
    slow,
)
from transformers.trainer_utils import set_seed  # noqa


set_seed(42)

UpperCAmelCase_     							= {'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'}

UpperCAmelCase_     							= 'zero2'
UpperCAmelCase_     							= 'zero3'
UpperCAmelCase_     							= [ZEROa, ZEROa]




def 		lowerCAmelCase_    (  __UpperCAmelCase:			Dict		,   __UpperCAmelCase:			Optional[Any]		,   __UpperCAmelCase:			List[str]      )      ->	List[str]:
    # customize the test name generator function as we want both params to appear in the sub-test
    # name, as by default it shows only the first param
    UpperCamelCase__							:				List[Any]          =      parameterized.to_safe_name('''_'''.join(str(__UpperCAmelCase      ) for x in param.args      )      )
    return f"{func.__name__}_{param_based_name}"


# Cartesian-product of zero stages with models to test
UpperCAmelCase_     							= list(itertools.product(stages, models.keys()))






@slow
@require_deepspeed
@require_torch_gpu
class     lowercase__       (	__lowerCamelCase				):

   '''simple docstring'''


   @parameterized.expand(__magic_name__,		name_func=__magic_name__							)
   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__							) ->      Union[str, Any]:






       """simple docstring"""
       self.run_and_check(
           stage=__magic_name__,		model=__magic_name__,		distributed=__magic_name__,		fpaa=__magic_name__,		)




   @require_torch_multi_gpu
   @parameterized.expand(__magic_name__,		name_func=__magic_name__							)
   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__							) ->      Optional[int]:






       """simple docstring"""
       self.run_and_check(
           stage=__magic_name__,		model=__magic_name__,		distributed=__magic_name__,		fpaa=__magic_name__,		)




   @parameterized.expand(__magic_name__,		name_func=__magic_name__							)
   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__							) ->      Union[str, Any]:






       """simple docstring"""
       self.run_and_check(
           stage=__magic_name__,		model=__magic_name__,		distributed=__magic_name__,		fpaa=__magic_name__,		)




   @require_torch_multi_gpu
   @parameterized.expand(__magic_name__,		name_func=__magic_name__							)
   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__							) ->      str:






       """simple docstring"""
       self.run_and_check(
           stage=__magic_name__,		model=__magic_name__,		distributed=__magic_name__,		fpaa=__magic_name__,		)




   def       UpperCamelCase__  (    self,		__magic_name__							) ->      str:






       """simple docstring"""
       # XXX: run_asr is premature and doesn't save any results
       # so all we check for now is that the process didn't fail
       pass




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__ = 10,		__magic_name__ = True,		__magic_name__ = True,		__magic_name__ = True,		) ->      str:






       """simple docstring"""
       UpperCamelCase__							:				List[str]          =      models[model]

       UpperCamelCase__							:				Union[str, Any]          =      self.run_trainer(
           stage=__magic_name__,		model_name=__magic_name__,		eval_steps=__magic_name__,		num_train_epochs=1,		distributed=__magic_name__,		fpaa=__magic_name__,		)

       self.do_checks(__magic_name__							)

       return output_dir




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__ = 10,		__magic_name__ = 1,		__magic_name__ = True,		__magic_name__ = True,		) ->      Tuple:






       """simple docstring"""
       UpperCamelCase__							:				Union[str, Any]          =      self.get_auto_remove_tmp_dir('''./xxx''',		after=__magic_name__							)
       UpperCamelCase__							:				Optional[Any]          =      f"\n            --model_name_or_path {model_name}\n            --dataset_name hf-internal-testing/librispeech_asr_dummy\n            --dataset_config_name clean\n            --train_split_name validation\n            --validation_split_name validation\n            --output_dir {output_dir}\n            --num_train_epochs {str(__magic_name__							)}\n            --per_device_train_batch_size 2\n            --per_device_eval_batch_size 2\n            --evaluation_strategy steps\n            --learning_rate 5e-4\n            --warmup_steps 8\n            --orthography timit\n            --preprocessing_num_workers 1\n            --group_by_length\n            --freeze_feature_extractor\n            --report_to none\n            --save_steps 0\n            --eval_steps {eval_steps}\n            --report_to none\n        ".split()

       if fpaa:
           args.extend(['''--fp16''']							)

       # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true,
       # hence the separate config files
       UpperCamelCase__							:				str          =      f"--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json".split()
       UpperCamelCase__							:				Dict          =      [f"{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"]
       UpperCamelCase__							:				Union[str, Any]          =      self.get_launcher(__magic_name__							)

       UpperCamelCase__							:				List[str]          =      launcher + script + args + ds_args
       # keep for quick debug
       # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
       execute_subprocess_async(__magic_name__,		env=self.get_env()							)

       return output_dir




   def       UpperCamelCase__  (    self,		__magic_name__=False							) ->      Tuple:






       """simple docstring"""
       # 1. explicitly set --num_nodes=1 just in case these tests end up run on a multi-node setup
       # - it won't be able to handle that
       # 2. for now testing with just 2 gpus max (since some quality tests may give different
       # results with mode gpus because we use very little data)
       UpperCamelCase__							:				Union[str, Any]          =      min(2,		get_gpu_count()							) if distributed else 1
       return f"deepspeed --num_nodes 1 --num_gpus {num_gpus}".split()








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

   '''simple docstring'''


   def __init__(    self,		__magic_name__,		__magic_name__=13,		__magic_name__=7,		__magic_name__=True,		__magic_name__=True,		__magic_name__=True,		__magic_name__=True,		__magic_name__=99,		__magic_name__=32,		__magic_name__=2,		__magic_name__=4,		__magic_name__=37,		__magic_name__="gelu",		__magic_name__=0.1,		__magic_name__=0.1,		__magic_name__=512,		__magic_name__=16,		__magic_name__=2,		__magic_name__=0.02,		__magic_name__=3,		__magic_name__=4,		__magic_name__=None,		) ->      List[str]:






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




   def       UpperCamelCase__  (    self							) ->      Dict:






       """simple docstring"""
       UpperCamelCase__							:				Tuple          =      ids_tensor([self.batch_size, self.seq_length],		self.vocab_size							)

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

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

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

       UpperCamelCase__							:				Any          =      ConvBertConfig(
           vocab_size=self.vocab_size,		hidden_size=self.hidden_size,		num_hidden_layers=self.num_hidden_layers,		num_attention_heads=self.num_attention_heads,		intermediate_size=self.intermediate_size,		hidden_act=self.hidden_act,		hidden_dropout_prob=self.hidden_dropout_prob,		attention_probs_dropout_prob=self.attention_probs_dropout_prob,		max_position_embeddings=self.max_position_embeddings,		type_vocab_size=self.type_vocab_size,		initializer_range=self.initializer_range,		return_dict=__magic_name__,		)

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




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__							) ->      Tuple:






       """simple docstring"""
       UpperCamelCase__							:				Tuple          =      TFConvBertModel(config=__magic_name__							)
       UpperCamelCase__							:				str          =      {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}

       UpperCamelCase__							:				Any          =      [input_ids, input_mask]
       UpperCamelCase__							:				int          =      model(__magic_name__							)

       UpperCamelCase__							:				int          =      model(__magic_name__							)

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




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__							) ->      int:






       """simple docstring"""
       UpperCamelCase__							:				Any          =      TFConvBertForMaskedLM(config=__magic_name__							)
       UpperCamelCase__							:				List[str]          =      {
           '''input_ids''': input_ids,
           '''attention_mask''': input_mask,
           '''token_type_ids''': token_type_ids,
       }
       UpperCamelCase__							:				Tuple          =      model(__magic_name__							)
       self.parent.assertEqual(result.logits.shape,		(self.batch_size, self.seq_length, self.vocab_size)							)




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__							) ->      Dict:






       """simple docstring"""
       UpperCamelCase__							:				str          =      self.num_labels
       UpperCamelCase__							:				Optional[int]          =      TFConvBertForSequenceClassification(config=__magic_name__							)
       UpperCamelCase__							:				str          =      {
           '''input_ids''': input_ids,
           '''attention_mask''': input_mask,
           '''token_type_ids''': token_type_ids,
       }

       UpperCamelCase__							:				Any          =      model(__magic_name__							)
       self.parent.assertEqual(result.logits.shape,		(self.batch_size, self.num_labels)							)




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__							) ->      Tuple:






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




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__							) ->      Optional[int]:






       """simple docstring"""
       UpperCamelCase__							:				Optional[Any]          =      self.num_labels
       UpperCamelCase__							:				Any          =      TFConvBertForTokenClassification(config=__magic_name__							)
       UpperCamelCase__							:				str          =      {
           '''input_ids''': input_ids,
           '''attention_mask''': input_mask,
           '''token_type_ids''': token_type_ids,
       }
       UpperCamelCase__							:				Dict          =      model(__magic_name__							)
       self.parent.assertEqual(result.logits.shape,		(self.batch_size, self.seq_length, self.num_labels)							)




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__							) ->      str:






       """simple docstring"""
       UpperCamelCase__							:				Union[str, Any]          =      TFConvBertForQuestionAnswering(config=__magic_name__							)
       UpperCamelCase__							:				Optional[Any]          =      {
           '''input_ids''': input_ids,
           '''attention_mask''': input_mask,
           '''token_type_ids''': token_type_ids,
       }

       UpperCamelCase__							:				List[str]          =      model(__magic_name__							)
       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							) ->      str:






       """simple docstring"""
       UpperCamelCase__							:				Any          =      self.prepare_config_and_inputs()
       (
           (
           UpperCamelCase__
       )   ,(
           UpperCamelCase__
       )   ,(
           UpperCamelCase__
       )   ,(
           UpperCamelCase__
       )   ,(
           UpperCamelCase__
       )   ,(
           UpperCamelCase__
       )   ,(
           UpperCamelCase__
       )   ,
       )							:				Any          =      config_and_inputs
       UpperCamelCase__							:				List[str]          =      {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
       return config, inputs_dict






@require_tf
class     lowercase__       (	__lowerCamelCase			,				__lowerCamelCase			,				unittest.TestCase				):

   '''simple docstring'''


   a						:							Union[str, Any]   		=		(
       (
           TFConvBertModel,
           TFConvBertForMaskedLM,
           TFConvBertForQuestionAnswering,
           TFConvBertForSequenceClassification,
           TFConvBertForTokenClassification,
           TFConvBertForMultipleChoice,
       )
       if is_tf_available()
       else ()
   )
   a						:							int   		=		(
       {
           "feature-extraction": TFConvBertModel,
           "fill-mask": TFConvBertForMaskedLM,
           "question-answering": TFConvBertForQuestionAnswering,
           "text-classification": TFConvBertForSequenceClassification,
           "token-classification": TFConvBertForTokenClassification,
           "zero-shot": TFConvBertForSequenceClassification,
       }
       if is_tf_available()
       else {}
   )
   a						:							Optional[Any]   		=		False
   a						:							List[str]   		=		False
   a						:							List[Any]   		=		False




   def       UpperCamelCase__  (    self							) ->      Optional[Any]:






       """simple docstring"""
       UpperCamelCase__							:				List[str]          =      TFConvBertModelTester(self							)
       UpperCamelCase__							:				Optional[int]          =      ConfigTester(self,		config_class=__magic_name__,		hidden_size=37							)




   def       UpperCamelCase__  (    self							) ->      int:






       """simple docstring"""
       self.config_tester.run_common_tests()




   def       UpperCamelCase__  (    self							) ->      List[Any]:






       """simple docstring"""
       UpperCamelCase__							:				Any          =      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__magic_name__							)




   def       UpperCamelCase__  (    self							) ->      Tuple:






       """simple docstring"""
       UpperCamelCase__							:				str          =      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_lm(*__magic_name__							)




   def       UpperCamelCase__  (    self							) ->      Dict:






       """simple docstring"""
       UpperCamelCase__							:				List[Any]          =      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_multiple_choice(*__magic_name__							)




   def       UpperCamelCase__  (    self							) ->      Optional[Any]:






       """simple docstring"""
       UpperCamelCase__							:				str          =      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_question_answering(*__magic_name__							)




   def       UpperCamelCase__  (    self							) ->      Tuple:






       """simple docstring"""
       UpperCamelCase__							:				Optional[int]          =      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_sequence_classification(*__magic_name__							)




   def       UpperCamelCase__  (    self							) ->      Dict:






       """simple docstring"""
       UpperCamelCase__							:				str          =      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_token_classification(*__magic_name__							)




   @slow
   def       UpperCamelCase__  (    self							) ->      Optional[int]:






       """simple docstring"""
       UpperCamelCase__   ,UpperCamelCase__							:				Tuple          =      self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase__							:				Union[str, Any]          =      True
       UpperCamelCase__							:				Optional[int]          =      True

       if hasattr(__magic_name__,		'''use_cache'''							):
           UpperCamelCase__							:				Union[str, Any]          =      True

       UpperCamelCase__							:				Tuple          =      getattr(self.model_tester,		'''encoder_seq_length''',		self.model_tester.seq_length							)
       UpperCamelCase__							:				Any          =      getattr(self.model_tester,		'''key_length''',		__magic_name__							)

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

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

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

               self.assertEqual(len(__magic_name__							),		__magic_name__							)

               UpperCamelCase__							:				Optional[Any]          =      getattr(
                   self.model_tester,		'''expected_num_hidden_layers''',		self.model_tester.num_hidden_layers + 1							)

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

               self.assertEqual(len(__magic_name__							),		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							) ->      str:






       """simple docstring"""
       UpperCamelCase__							:				str          =      TFConvBertModel.from_pretrained('''YituTech/conv-bert-base'''							)
       self.assertIsNotNone(__magic_name__							)




   def       UpperCamelCase__  (    self							) ->      Dict:






       """simple docstring"""
       UpperCamelCase__   ,UpperCamelCase__							:				int          =      self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase__							:				str          =      True
       UpperCamelCase__							:				Union[str, Any]          =      getattr(self.model_tester,		'''decoder_seq_length''',		self.model_tester.seq_length							)
       UpperCamelCase__							:				str          =      getattr(self.model_tester,		'''encoder_seq_length''',		self.model_tester.seq_length							)
       UpperCamelCase__							:				List[str]          =      getattr(self.model_tester,		'''key_length''',		__magic_name__							)
       UpperCamelCase__							:				int          =      getattr(self.model_tester,		'''key_length''',		__magic_name__							)

       def check_decoder_attentions_output(__magic_name__							):
           UpperCamelCase__							:				List[str]          =      len(__magic_name__							)
           self.assertEqual(out_len % 2,		0							)
           UpperCamelCase__							:				Optional[Any]          =      outputs.decoder_attentions
           self.assertEqual(len(__magic_name__							),		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(__magic_name__							):
           UpperCamelCase__							:				int          =      [
               t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions)
           ]
           self.assertEqual(len(__magic_name__							),		self.model_tester.num_hidden_layers							)
           self.assertListEqual(
               list(attentions[0].shape[-3:]							),		[self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length],		)

       for model_class in self.all_model_classes:
           UpperCamelCase__							:				Dict          =      True
           UpperCamelCase__							:				str          =      False
           UpperCamelCase__							:				Optional[Any]          =      model_class(__magic_name__							)
           UpperCamelCase__							:				Dict          =      model(self._prepare_for_class(__magic_name__,		__magic_name__							)							)
           UpperCamelCase__							:				int          =      len(__magic_name__							)
           self.assertEqual(config.output_hidden_states,		__magic_name__							)
           check_encoder_attentions_output(__magic_name__							)

           if self.is_encoder_decoder:
               UpperCamelCase__							:				str          =      model_class(__magic_name__							)
               UpperCamelCase__							:				List[str]          =      model(self._prepare_for_class(__magic_name__,		__magic_name__							)							)
               self.assertEqual(config.output_hidden_states,		__magic_name__							)
               check_decoder_attentions_output(__magic_name__							)

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

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

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






@require_tf
class     lowercase__       (	unittest.TestCase				):

   '''simple docstring'''


   @slow
   def       UpperCamelCase__  (    self							) ->      int:






       """simple docstring"""
       UpperCamelCase__							:				Union[str, Any]          =      TFConvBertModel.from_pretrained('''YituTech/conv-bert-base'''							)
       UpperCamelCase__							:				Tuple          =      tf.constant([[0, 1, 2, 3, 4, 5]]							)
       UpperCamelCase__							:				int          =      model(__magic_name__							)[0]

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

       UpperCamelCase__							:				Union[str, Any]          =      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],		__magic_name__,		atol=1E-4							)

