


"""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 				UpperCamelCase_			:

 """simple docstring"""





 def __init__(				self    :       Optional[int]    ,    UpperCAmelCase__    :       Dict    ,    UpperCAmelCase__    :       Optional[Any]=1_3    ,    UpperCAmelCase__    :       str=7    ,    UpperCAmelCase__    :       int=True    ,    UpperCAmelCase__    :       List[str]=True    ,    UpperCAmelCase__    :       Tuple=True    ,    UpperCAmelCase__    :       Optional[int]=True    ,    UpperCAmelCase__    :       Optional[int]=9_9    ,    UpperCAmelCase__    :       int=3_2    ,    UpperCAmelCase__    :       Tuple=2    ,    UpperCAmelCase__    :       Union[str, Any]=4    ,    UpperCAmelCase__    :       Optional[int]=3_7    ,    UpperCAmelCase__    :       List[Any]="gelu"    ,    UpperCAmelCase__    :       Union[str, Any]=0.1    ,    UpperCAmelCase__    :       Union[str, Any]=0.1    ,    UpperCAmelCase__    :       List[Any]=5_1_2    ,    UpperCAmelCase__    :       Optional[int]=1_6    ,    UpperCAmelCase__    :       List[str]=2    ,    UpperCAmelCase__    :       Tuple=0.02    ,    UpperCAmelCase__    :       str=3    ,    UpperCAmelCase__    :       List[Any]=4    ,    UpperCAmelCase__    :       Tuple=None    ,    ) ->			Tuple:
      __SCREAMING_SNAKE_CASE		     =       parent
      __SCREAMING_SNAKE_CASE		     =       1_3
      __SCREAMING_SNAKE_CASE		     =       7
      __SCREAMING_SNAKE_CASE		     =       True
      __SCREAMING_SNAKE_CASE		     =       True
      __SCREAMING_SNAKE_CASE		     =       True
      __SCREAMING_SNAKE_CASE		     =       True
      __SCREAMING_SNAKE_CASE		     =       9_9
      __SCREAMING_SNAKE_CASE		     =       3_8_4
      __SCREAMING_SNAKE_CASE		     =       2
      __SCREAMING_SNAKE_CASE		     =       4
      __SCREAMING_SNAKE_CASE		     =       3_7
      __SCREAMING_SNAKE_CASE		     =       "gelu"
      __SCREAMING_SNAKE_CASE		     =       0.1
      __SCREAMING_SNAKE_CASE		     =       0.1
      __SCREAMING_SNAKE_CASE		     =       5_1_2
      __SCREAMING_SNAKE_CASE		     =       1_6
      __SCREAMING_SNAKE_CASE		     =       2
      __SCREAMING_SNAKE_CASE		     =       0.02
      __SCREAMING_SNAKE_CASE		     =       3
      __SCREAMING_SNAKE_CASE		     =       4
      __SCREAMING_SNAKE_CASE		     =       1_2_8
      __SCREAMING_SNAKE_CASE		     =       2
      __SCREAMING_SNAKE_CASE		     =       9
      __SCREAMING_SNAKE_CASE		     =       1
      __SCREAMING_SNAKE_CASE		     =       None




 def 						UpperCAmelCase_   (				self    :       Tuple     ) ->			Optional[Any]:
      __SCREAMING_SNAKE_CASE		     =       ids_tensor([self.batch_size, self.seq_length]    ,    self.vocab_size     )

      __SCREAMING_SNAKE_CASE		     =       None
      if self.use_input_mask:
           __SCREAMING_SNAKE_CASE		     =       random_attention_mask([self.batch_size, self.seq_length]     )

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

      __SCREAMING_SNAKE_CASE		     =       None
      __SCREAMING_SNAKE_CASE		     =       None
      __SCREAMING_SNAKE_CASE		     =       None
      if self.use_labels:
           __SCREAMING_SNAKE_CASE		     =       ids_tensor([self.batch_size]    ,    self.type_sequence_label_size     )
           __SCREAMING_SNAKE_CASE		     =       ids_tensor([self.batch_size, self.seq_length]    ,    self.num_labels     )
           __SCREAMING_SNAKE_CASE		     =       ids_tensor([self.batch_size]    ,    self.num_choices     )

      __SCREAMING_SNAKE_CASE		     =       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 						UpperCAmelCase_   (				self    :       Optional[int]    ,    UpperCAmelCase__    :       Union[str, Any]    ,    UpperCAmelCase__    :       int    ,    UpperCAmelCase__    :       Any    ,    UpperCAmelCase__    :       Union[str, Any]    ,    UpperCAmelCase__    :       Tuple    ,    UpperCAmelCase__    :       List[str]    ,    UpperCAmelCase__    :       List[str]     ) ->			Any:
      __SCREAMING_SNAKE_CASE		     =       TFConvBertModel(config=UpperCAmelCase__     )
      __SCREAMING_SNAKE_CASE		     =       {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}

      __SCREAMING_SNAKE_CASE		     =       [input_ids, input_mask]
      __SCREAMING_SNAKE_CASE		     =       model(UpperCAmelCase__     )

      __SCREAMING_SNAKE_CASE		     =       model(UpperCAmelCase__     )

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




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




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

      __SCREAMING_SNAKE_CASE		     =       model(UpperCAmelCase__     )
      self.parent.assertEqual(result.logits.shape    ,    (self.batch_size, self.num_labels)     )




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




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




 def 						UpperCAmelCase_   (				self    :       List[str]    ,    UpperCAmelCase__    :       List[str]    ,    UpperCAmelCase__    :       Optional[int]    ,    UpperCAmelCase__    :       Dict    ,    UpperCAmelCase__    :       Tuple    ,    UpperCAmelCase__    :       str    ,    UpperCAmelCase__    :       Optional[int]    ,    UpperCAmelCase__    :       int     ) ->			Optional[Any]:
      __SCREAMING_SNAKE_CASE		     =       TFConvBertForQuestionAnswering(config=UpperCAmelCase__     )
      __SCREAMING_SNAKE_CASE		     =       {
          "input_ids": input_ids,
          "attention_mask": input_mask,
          "token_type_ids": token_type_ids,
      }

      __SCREAMING_SNAKE_CASE		     =       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 						UpperCAmelCase_   (				self    :       Dict     ) ->			Dict:
      __SCREAMING_SNAKE_CASE		     =       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		
      )     ,								
      )		     =       config_and_inputs
      __SCREAMING_SNAKE_CASE		     =       {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
      return config, inputs_dict




@require_tf
class 				UpperCamelCase_			(				__UpperCAmelCase    ,						__UpperCAmelCase    ,						unittest.TestCase):

 """simple docstring"""





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




 def 						UpperCAmelCase_   (				self    :       Tuple     ) ->			int:
      __SCREAMING_SNAKE_CASE		     =       TFConvBertModelTester(self     )
      __SCREAMING_SNAKE_CASE		     =       ConfigTester(self    ,    config_class=UpperCAmelCase__    ,    hidden_size=3_7     )




 def 						UpperCAmelCase_   (				self    :       List[str]     ) ->			Dict:
      self.config_tester.run_common_tests()




 def 						UpperCAmelCase_   (				self    :       str     ) ->			Optional[Any]:
      __SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*UpperCAmelCase__     )




 def 						UpperCAmelCase_   (				self    :       Dict     ) ->			Optional[Any]:
      __SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase__     )




 def 						UpperCAmelCase_   (				self    :       Optional[int]     ) ->			Optional[int]:
      __SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_multiple_choice(*UpperCAmelCase__     )




 def 						UpperCAmelCase_   (				self    :       List[str]     ) ->			Union[str, Any]:
      __SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase__     )




 def 						UpperCAmelCase_   (				self    :       Any     ) ->			List[Any]:
      __SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase__     )




 def 						UpperCAmelCase_   (				self    :       Any     ) ->			str:
      __SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase__     )




 @slow
 def 						UpperCAmelCase_   (				self    :       Dict     ) ->			Tuple:
      __SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs_for_common()
      __SCREAMING_SNAKE_CASE		     =       True
      __SCREAMING_SNAKE_CASE		     =       True

      if hasattr(UpperCAmelCase__    ,    "use_cache"     ):
           __SCREAMING_SNAKE_CASE		     =       True

      __SCREAMING_SNAKE_CASE		     =       getattr(self.model_tester    ,    "encoder_seq_length"    ,    self.model_tester.seq_length     )
      __SCREAMING_SNAKE_CASE		     =       getattr(self.model_tester    ,    "key_length"    ,    UpperCAmelCase__     )

      for model_class in self.all_model_classes:
           __SCREAMING_SNAKE_CASE		     =       self._prepare_for_class(UpperCAmelCase__    ,    UpperCAmelCase__     )
           __SCREAMING_SNAKE_CASE		     =       model_class(UpperCAmelCase__     )
           __SCREAMING_SNAKE_CASE		     =       len(model(UpperCAmelCase__     )     )

           with tempfile.TemporaryDirectory() as tmpdirname:
                model.save_pretrained(UpperCAmelCase__    ,    saved_model=UpperCAmelCase__     )
                __SCREAMING_SNAKE_CASE		     =       os.path.join(UpperCAmelCase__    ,    "saved_model"    ,    "1"     )
                __SCREAMING_SNAKE_CASE		     =       tf.keras.models.load_model(UpperCAmelCase__     )
                __SCREAMING_SNAKE_CASE		     =       model(UpperCAmelCase__     )

                if self.is_encoder_decoder:
                     __SCREAMING_SNAKE_CASE		     =       outputs["encoder_hidden_states"]
                     __SCREAMING_SNAKE_CASE		     =       outputs["encoder_attentions"]
                else:
                     __SCREAMING_SNAKE_CASE		     =       outputs["hidden_states"]
                     __SCREAMING_SNAKE_CASE		     =       outputs["attentions"]

                self.assertEqual(len(UpperCAmelCase__     )    ,    UpperCAmelCase__     )

                __SCREAMING_SNAKE_CASE		     =       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 						UpperCAmelCase_   (				self    :       Any     ) ->			Union[str, Any]:
      __SCREAMING_SNAKE_CASE		     =       TFConvBertModel.from_pretrained("YituTech/conv-bert-base"     )
      self.assertIsNotNone(UpperCAmelCase__     )




 def 						UpperCAmelCase_   (				self    :       int     ) ->			Dict:
      __SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs_for_common()
      __SCREAMING_SNAKE_CASE		     =       True
      __SCREAMING_SNAKE_CASE		     =       getattr(self.model_tester    ,    "decoder_seq_length"    ,    self.model_tester.seq_length     )
      __SCREAMING_SNAKE_CASE		     =       getattr(self.model_tester    ,    "encoder_seq_length"    ,    self.model_tester.seq_length     )
      __SCREAMING_SNAKE_CASE		     =       getattr(self.model_tester    ,    "key_length"    ,    UpperCAmelCase__     )
      __SCREAMING_SNAKE_CASE		     =       getattr(self.model_tester    ,    "key_length"    ,    UpperCAmelCase__     )

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

           if self.is_encoder_decoder:
                __SCREAMING_SNAKE_CASE		     =       model_class(UpperCAmelCase__     )
                __SCREAMING_SNAKE_CASE		     =       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"]
           __SCREAMING_SNAKE_CASE		     =       True
           __SCREAMING_SNAKE_CASE		     =       model_class(UpperCAmelCase__     )
           __SCREAMING_SNAKE_CASE		     =       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
           __SCREAMING_SNAKE_CASE		     =       True
           __SCREAMING_SNAKE_CASE		     =       True
           __SCREAMING_SNAKE_CASE		     =       model_class(UpperCAmelCase__     )
           __SCREAMING_SNAKE_CASE		     =       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 				UpperCamelCase_			(				unittest.TestCase):

 """simple docstring"""





 @slow
 def 						UpperCAmelCase_   (				self    :       str     ) ->			Optional[int]:
      __SCREAMING_SNAKE_CASE		     =       TFConvBertModel.from_pretrained("YituTech/conv-bert-base"     )
      __SCREAMING_SNAKE_CASE		     =       tf.constant([[0, 1, 2, 3, 4, 5]]     )
      __SCREAMING_SNAKE_CASE		     =       model(UpperCAmelCase__     )[0]

      __SCREAMING_SNAKE_CASE		     =       [1, 6, 7_6_8]
      self.assertEqual(output.shape    ,    UpperCAmelCase__     )

      __SCREAMING_SNAKE_CASE		     =       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     )




"""simple docstring"""







import csv
from collections import defaultdict
from dataclasses import dataclass, field
from typing import List, Optional

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import ScalarFormatter

from transformers import HfArgumentParser




def      UpperCAmelCase__ (lowerCAmelCase_=None						,		lowerCAmelCase_=None     ):




					'''simple docstring'''


					return field(default_factory=lambda: default						,		metadata=lowerCAmelCase_     )




@dataclass
class 				UpperCamelCase_			:

	"""simple docstring"""





	snake_case__       :						str					      =    field(
	    metadata={"help": "The csv file to plot."}    ,						)
	snake_case__       :						bool					      =    field(
	    default=UpperCamelCase    ,						metadata={"help": "Whether to plot along batch size or sequence length. Defaults to sequence length."}    ,						)
	snake_case__       :						bool					      =    field(
	    default=UpperCamelCase    ,						metadata={"help": "Whether the csv file has time results or memory results. Defaults to memory results."}    ,						)
	snake_case__       :						bool					      =    field(
	    default=UpperCamelCase    ,						metadata={"help": "Disable logarithmic scale when plotting"}    ,						)
	snake_case__       :						bool					      =    field(
	    default=UpperCamelCase    ,						metadata={
	        "help": "Whether the csv file has training results or inference results. Defaults to inference results."
	    }    ,						)
	snake_case__       :						Optional[str]					      =    field(
	    default=UpperCamelCase    ,						metadata={"help": "Filename under which the plot will be saved. If unused no plot is saved."}    ,						)
	snake_case__       :						Optional[List[str]]					      =    list_field(
	    default=UpperCamelCase    ,						metadata={"help": "List of model names that are used instead of the ones in the csv file."})




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					try:
										int(lowerCAmelCase_     )
										return True
					except ValueError:
										return False




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					try:
										float(lowerCAmelCase_     )
										return True
					except ValueError:
										return False




class 				UpperCamelCase_			:

	"""simple docstring"""





	def __init__(				self    :       str    ,    UpperCAmelCase__    :       Dict     ) ->			Optional[Any]:
						__SCREAMING_SNAKE_CASE		     =       args
						__SCREAMING_SNAKE_CASE		     =       defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}}     )

						with open(self.args.csv_file    ,    newline=""     ) as csv_file:
											__SCREAMING_SNAKE_CASE		     =       csv.DictReader(UpperCAmelCase__     )
											for row in reader:
																__SCREAMING_SNAKE_CASE		     =       row["model"]
																self.result_dict[model_name]["bsz"].append(int(row["batch_size"]     )     )
																self.result_dict[model_name]["seq_len"].append(int(row["sequence_length"]     )     )
																if can_convert_to_int(row["result"]     ):
																					# value is not None
																					__SCREAMING_SNAKE_CASE		     =       int(row["result"]     )
																elif can_convert_to_float(row["result"]     ):
																					# value is not None
																					__SCREAMING_SNAKE_CASE		     =       float(row["result"]     )




	def 						UpperCAmelCase_   (				self    :       List[str]     ) ->			Tuple:
						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       plt.subplots()
						__SCREAMING_SNAKE_CASE		     =       "Time usage" if self.args.is_time else "Memory usage"
						__SCREAMING_SNAKE_CASE		     =       title_str + " for training" if self.args.is_train else title_str + " for inference"

						if not self.args.no_log_scale:
											# set logarithm scales
											ax.set_xscale("log"     )
											ax.set_yscale("log"     )

						for axis in [ax.xaxis, ax.yaxis]:
											axis.set_major_formatter(ScalarFormatter()     )

						for model_name_idx, model_name in enumerate(self.result_dict.keys()     ):
											__SCREAMING_SNAKE_CASE		     =       sorted(set(self.result_dict[model_name]["bsz"]     )     )
											__SCREAMING_SNAKE_CASE		     =       sorted(set(self.result_dict[model_name]["seq_len"]     )     )
											__SCREAMING_SNAKE_CASE		     =       self.result_dict[model_name]["result"]

											((__SCREAMING_SNAKE_CASE)     ,						(__SCREAMING_SNAKE_CASE))		     =       (
											    (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes)
											)

											__SCREAMING_SNAKE_CASE		     =       (
											    model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx]
											)

											for inner_loop_value in inner_loop_array:
																if self.args.plot_along_batch:
																					__SCREAMING_SNAKE_CASE		     =       np.asarray(
																					    [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results]    ,    dtype=UpperCAmelCase__    ,    )
																else:
																					__SCREAMING_SNAKE_CASE		     =       np.asarray(
																					    [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results]    ,    dtype=np.floataa    ,    )

																((__SCREAMING_SNAKE_CASE)     ,						(__SCREAMING_SNAKE_CASE))		     =       (
																    ("batch_size", "len") if self.args.plot_along_batch else ("in #tokens", "bsz")
																)

																__SCREAMING_SNAKE_CASE		     =       np.asarray(UpperCAmelCase__    ,    UpperCAmelCase__     )[: len(UpperCAmelCase__     )]
																plt.scatter(
																    UpperCAmelCase__    ,    UpperCAmelCase__    ,    label=F"""{label_model_name} - {inner_loop_label}: {inner_loop_value}"""     )
																plt.plot(UpperCAmelCase__    ,    UpperCAmelCase__    ,    "--"     )

											title_str += F""" {label_model_name} vs."""

						__SCREAMING_SNAKE_CASE		     =       title_str[:-4]
						__SCREAMING_SNAKE_CASE		     =       "Time in s" if self.args.is_time else "Memory in MB"

						# plot
						plt.title(UpperCAmelCase__     )
						plt.xlabel(UpperCAmelCase__     )
						plt.ylabel(UpperCAmelCase__     )
						plt.legend()

						if self.args.figure_png_file is not None:
											plt.savefig(self.args.figure_png_file     )
						else:
											plt.show()




def      UpperCAmelCase__ ():




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE		     =       HfArgumentParser(lowerCAmelCase_     )
					__SCREAMING_SNAKE_CASE		     =       parser.parse_args_into_dataclasses()[0]
					__SCREAMING_SNAKE_CASE		     =       Plot(args=lowerCAmelCase_     )
					plot.plot()


if __name__ == "__main__":
		main()
