



"""simple docstring"""
import unittest

from transformers import MobileBertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch

       from transformers import (
           MODEL_FOR_PRETRAINING_MAPPING,
           MobileBertForMaskedLM,
           MobileBertForMultipleChoice,
           MobileBertForNextSentencePrediction,
           MobileBertForPreTraining,
           MobileBertForQuestionAnswering,
           MobileBertForSequenceClassification,
           MobileBertForTokenClassification,
           MobileBertModel,
       )


class       SCREAMING_SNAKE_CASE__       :

    def __init__( self	: List[Any]       ,     lowerCAmelCase_	: int       ,     lowerCAmelCase_	: List[str]=1_3       ,     lowerCAmelCase_	: Tuple=7       ,     lowerCAmelCase_	: List[Any]=True       ,     lowerCAmelCase_	: List[Any]=True       ,     lowerCAmelCase_	: Dict=True       ,     lowerCAmelCase_	: Optional[int]=True       ,     lowerCAmelCase_	: str=9_9       ,     lowerCAmelCase_	: Dict=6_4       ,     lowerCAmelCase_	: Any=3_2       ,     lowerCAmelCase_	: str=5       ,     lowerCAmelCase_	: int=4       ,     lowerCAmelCase_	: List[Any]=3_7       ,     lowerCAmelCase_	: Any="gelu"       ,     lowerCAmelCase_	: Dict=0.1       ,     lowerCAmelCase_	: List[str]=0.1       ,     lowerCAmelCase_	: str=5_1_2       ,     lowerCAmelCase_	: Any=1_6       ,     lowerCAmelCase_	: str=2       ,     lowerCAmelCase_	: int=0.02       ,     lowerCAmelCase_	: Union[str, Any]=3       ,     lowerCAmelCase_	: Optional[Any]=4       ,     lowerCAmelCase_	: List[Any]=None       ,     ):







      """simple docstring"""







      lowercase_	    =       parent
      lowercase_	    =       batch_size
      lowercase_	    =       seq_length
      lowercase_	    =       is_training
      lowercase_	    =       use_input_mask
      lowercase_	    =       use_token_type_ids
      lowercase_	    =       use_labels
      lowercase_	    =       vocab_size
      lowercase_	    =       hidden_size
      lowercase_	    =       embedding_size
      lowercase_	    =       num_hidden_layers
      lowercase_	    =       num_attention_heads
      lowercase_	    =       intermediate_size
      lowercase_	    =       hidden_act
      lowercase_	    =       hidden_dropout_prob
      lowercase_	    =       attention_probs_dropout_prob
      lowercase_	    =       max_position_embeddings
      lowercase_	    =       type_vocab_size
      lowercase_	    =       type_sequence_label_size
      lowercase_	    =       initializer_range
      lowercase_	    =       num_labels
      lowercase_	    =       num_choices
      lowercase_	    =       scope

    def     _UpperCAmelCase		( self	: str):







      """simple docstring"""







      lowercase_	    =       ids_tensor([self.batch_size, self.seq_length]       ,     self.vocab_size)

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

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

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

      lowercase_	    =       self.get_config()

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

    def     _UpperCAmelCase		( self	: int):







      """simple docstring"""







      return MobileBertConfig(
          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       ,     embedding_size=self.embedding_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       ,     is_decoder=snake_case_       ,     initializer_range=self.initializer_range       ,     )

    def     _UpperCAmelCase		( self	: str       ,     lowerCAmelCase_	: Tuple       ,     lowerCAmelCase_	: List[str]       ,     lowerCAmelCase_	: int       ,     lowerCAmelCase_	: int       ,     lowerCAmelCase_	: Any       ,     lowerCAmelCase_	: List[Any]       ,     lowerCAmelCase_	: Any):







      """simple docstring"""







      lowercase_	    =       MobileBertModel(config=snake_case_)
      model.to(snake_case_)
      model.eval()
      lowercase_	    =       model(snake_case_       ,     attention_mask=snake_case_       ,     token_type_ids=snake_case_)
      lowercase_	    =       model(snake_case_       ,     token_type_ids=snake_case_)
      lowercase_	    =       model(snake_case_)

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

    def     _UpperCAmelCase		( self	: Any       ,     lowerCAmelCase_	: Dict       ,     lowerCAmelCase_	: Optional[Any]       ,     lowerCAmelCase_	: Tuple       ,     lowerCAmelCase_	: Dict       ,     lowerCAmelCase_	: Tuple       ,     lowerCAmelCase_	: str       ,     lowerCAmelCase_	: List[Any]):







      """simple docstring"""







      lowercase_	    =       MobileBertForMaskedLM(config=snake_case_)
      model.to(snake_case_)
      model.eval()
      lowercase_	    =       model(snake_case_       ,     attention_mask=snake_case_       ,     token_type_ids=snake_case_       ,     labels=snake_case_)
      self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.seq_length, self.vocab_size))

    def     _UpperCAmelCase		( self	: Tuple       ,     lowerCAmelCase_	: Any       ,     lowerCAmelCase_	: Dict       ,     lowerCAmelCase_	: List[Any]       ,     lowerCAmelCase_	: Any       ,     lowerCAmelCase_	: Union[str, Any]       ,     lowerCAmelCase_	: Optional[int]       ,     lowerCAmelCase_	: Dict):







      """simple docstring"""







      lowercase_	    =       MobileBertForNextSentencePrediction(config=snake_case_)
      model.to(snake_case_)
      model.eval()
      lowercase_	    =       model(
          snake_case_       ,     attention_mask=snake_case_       ,     token_type_ids=snake_case_       ,     labels=snake_case_       ,     )
      self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, 2))

    def     _UpperCAmelCase		( self	: Any       ,     lowerCAmelCase_	: Dict       ,     lowerCAmelCase_	: Optional[int]       ,     lowerCAmelCase_	: Any       ,     lowerCAmelCase_	: Any       ,     lowerCAmelCase_	: Union[str, Any]       ,     lowerCAmelCase_	: Dict       ,     lowerCAmelCase_	: Optional[Any]):







      """simple docstring"""







      lowercase_	    =       MobileBertForPreTraining(config=snake_case_)
      model.to(snake_case_)
      model.eval()
      lowercase_	    =       model(
          snake_case_       ,     attention_mask=snake_case_       ,     token_type_ids=snake_case_       ,     labels=snake_case_       ,     next_sentence_label=snake_case_       ,     )
      self.parent.assertEqual(result.prediction_logits.shape       ,     (self.batch_size, self.seq_length, self.vocab_size))
      self.parent.assertEqual(result.seq_relationship_logits.shape       ,     (self.batch_size, 2))

    def     _UpperCAmelCase		( self	: Dict       ,     lowerCAmelCase_	: Tuple       ,     lowerCAmelCase_	: Any       ,     lowerCAmelCase_	: Dict       ,     lowerCAmelCase_	: int       ,     lowerCAmelCase_	: int       ,     lowerCAmelCase_	: str       ,     lowerCAmelCase_	: str):







      """simple docstring"""







      lowercase_	    =       MobileBertForQuestionAnswering(config=snake_case_)
      model.to(snake_case_)
      model.eval()
      lowercase_	    =       model(
          snake_case_       ,     attention_mask=snake_case_       ,     token_type_ids=snake_case_       ,     start_positions=snake_case_       ,     end_positions=snake_case_       ,     )
      self.parent.assertEqual(result.start_logits.shape       ,     (self.batch_size, self.seq_length))
      self.parent.assertEqual(result.end_logits.shape       ,     (self.batch_size, self.seq_length))

    def     _UpperCAmelCase		( self	: Optional[int]       ,     lowerCAmelCase_	: Any       ,     lowerCAmelCase_	: List[str]       ,     lowerCAmelCase_	: List[Any]       ,     lowerCAmelCase_	: str       ,     lowerCAmelCase_	: Any       ,     lowerCAmelCase_	: Tuple       ,     lowerCAmelCase_	: Optional[int]):







      """simple docstring"""







      lowercase_	    =       self.num_labels
      lowercase_	    =       MobileBertForSequenceClassification(snake_case_)
      model.to(snake_case_)
      model.eval()
      lowercase_	    =       model(snake_case_       ,     attention_mask=snake_case_       ,     token_type_ids=snake_case_       ,     labels=snake_case_)
      self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.num_labels))

    def     _UpperCAmelCase		( self	: List[Any]       ,     lowerCAmelCase_	: Optional[int]       ,     lowerCAmelCase_	: str       ,     lowerCAmelCase_	: Dict       ,     lowerCAmelCase_	: List[Any]       ,     lowerCAmelCase_	: Optional[Any]       ,     lowerCAmelCase_	: Dict       ,     lowerCAmelCase_	: Optional[int]):







      """simple docstring"""







      lowercase_	    =       self.num_labels
      lowercase_	    =       MobileBertForTokenClassification(config=snake_case_)
      model.to(snake_case_)
      model.eval()
      lowercase_	    =       model(snake_case_       ,     attention_mask=snake_case_       ,     token_type_ids=snake_case_       ,     labels=snake_case_)
      self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.seq_length, self.num_labels))

    def     _UpperCAmelCase		( self	: Union[str, Any]       ,     lowerCAmelCase_	: List[str]       ,     lowerCAmelCase_	: Any       ,     lowerCAmelCase_	: Optional[Any]       ,     lowerCAmelCase_	: Optional[Any]       ,     lowerCAmelCase_	: Any       ,     lowerCAmelCase_	: Dict       ,     lowerCAmelCase_	: Union[str, Any]):







      """simple docstring"""







      lowercase_	    =       self.num_choices
      lowercase_	    =       MobileBertForMultipleChoice(config=snake_case_)
      model.to(snake_case_)
      model.eval()
      lowercase_	    =       input_ids.unsqueeze(1).expand(-1       ,     self.num_choices       ,     -1).contiguous()
      lowercase_	    =       token_type_ids.unsqueeze(1).expand(-1       ,     self.num_choices       ,     -1).contiguous()
      lowercase_	    =       input_mask.unsqueeze(1).expand(-1       ,     self.num_choices       ,     -1).contiguous()
      lowercase_	    =       model(
          snake_case_       ,     attention_mask=snake_case_       ,     token_type_ids=snake_case_       ,     labels=snake_case_       ,     )
      self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.num_choices))




    def     _UpperCAmelCase		( self	: Optional[Any]):







      """simple docstring"""







      lowercase_	    =       self.prepare_config_and_inputs()
      (
          lowercase_       
      )	    =       config_and_inputs
      lowercase_	    =       {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
      return config, inputs_dict







@require_torch
class       SCREAMING_SNAKE_CASE__       (							__lowercase					,     __lowercase					,     unittest.TestCase      ):
    lowercase__          =      (
        (
            MobileBertModel,
            MobileBertForMaskedLM,
            MobileBertForMultipleChoice,
            MobileBertForNextSentencePrediction,
            MobileBertForPreTraining,
            MobileBertForQuestionAnswering,
            MobileBertForSequenceClassification,
            MobileBertForTokenClassification,
        )
        if is_torch_available()
        else ()
    )
    lowercase__          =      (
        {
            "feature-extraction": MobileBertModel,
            "fill-mask": MobileBertForMaskedLM,
            "question-answering": MobileBertForQuestionAnswering,
            "text-classification": MobileBertForSequenceClassification,
            "token-classification": MobileBertForTokenClassification,
            "zero-shot": MobileBertForSequenceClassification,
        }
        if is_torch_available()
        else {}
    )
    lowercase__          =      True

    def     _UpperCAmelCase		( self	: str       ,     lowerCAmelCase_	: Tuple       ,     lowerCAmelCase_	: List[Any]       ,     lowerCAmelCase_	: Union[str, Any]=False):







      """simple docstring"""







      lowercase_	    =       super()._prepare_for_class(snake_case_       ,     snake_case_       ,     return_labels=snake_case_)

      if return_labels:
        if model_class in get_values(snake_case_):
          lowercase_	    =       torch.zeros(
              (self.model_tester.batch_size, self.model_tester.seq_length)       ,     dtype=torch.long       ,     device=snake_case_)
          lowercase_	    =       torch.zeros(
              self.model_tester.batch_size       ,     dtype=torch.long       ,     device=snake_case_)
      return inputs_dict

    def     _UpperCAmelCase		( self	: Tuple):







      """simple docstring"""







      lowercase_	    =       MobileBertModelTester(self)
      lowercase_	    =       ConfigTester(self       ,     config_class=snake_case_       ,     hidden_size=3_7)

    def     _UpperCAmelCase		( self	: Union[str, Any]):







      """simple docstring"""







      self.config_tester.run_common_tests()

    def     _UpperCAmelCase		( self	: Optional[Any]):







      """simple docstring"""







      lowercase_	    =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mobilebert_model(*snake_case_)

    def     _UpperCAmelCase		( self	: str):







      """simple docstring"""







      lowercase_	    =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mobilebert_for_masked_lm(*snake_case_)

    def     _UpperCAmelCase		( self	: Tuple):







      """simple docstring"""







      lowercase_	    =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mobilebert_for_multiple_choice(*snake_case_)

    def     _UpperCAmelCase		( self	: Dict):







      """simple docstring"""







      lowercase_	    =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*snake_case_)

    def     _UpperCAmelCase		( self	: int):







      """simple docstring"""







      lowercase_	    =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mobilebert_for_pretraining(*snake_case_)

    def     _UpperCAmelCase		( self	: List[Any]):







      """simple docstring"""







      lowercase_	    =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mobilebert_for_question_answering(*snake_case_)

    def     _UpperCAmelCase		( self	: int):







      """simple docstring"""







      lowercase_	    =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mobilebert_for_sequence_classification(*snake_case_)




    def     _UpperCAmelCase		( self	: Tuple):







      """simple docstring"""







      lowercase_	    =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mobilebert_for_token_classification(*snake_case_)







def 	_SCREAMING_SNAKE_CASE  (__lowerCAmelCase							)       ->  List[Any]:







  '''simple docstring'''


  return torch.tensor(
      lowerCAmelCase__       ,     dtype=torch.long       ,     device=lowerCAmelCase__       ,     )


UpperCAmelCase  :						List[Any]	=       1E-3


@require_torch
@require_sentencepiece
@require_tokenizers
class       SCREAMING_SNAKE_CASE__       (							unittest.TestCase      ):

    @slow
    def     _UpperCAmelCase		( self	: Any):







      """simple docstring"""







      lowercase_	    =       MobileBertModel.from_pretrained("""google/mobilebert-uncased""").to(snake_case_)
      lowercase_	    =       _long_tensor([[1_0_1, 7_1_1_0, 1_0_0_5, 1_0_5_6, 2_0_2_3, 1_1_3_3_3, 1_7_4_1_3, 1_0_2_9, 1_0_2]])
      with torch.no_grad():
        lowercase_	    =       model(snake_case_)[0]
      lowercase_	    =       torch.Size((1, 9, 5_1_2))
      self.assertEqual(output.shape       ,     snake_case_)
      lowercase_	    =       torch.tensor(
          [
              [
                  [-2.4736526E07, 8.2691656E04, 1.6521838E05],
                  [-5.7541704E-01, 3.9056022E00, 4.4011507E00],
                  [2.6047359E00, 1.5677652E00, -1.7324188E-01],
              ]
          ]       ,     device=snake_case_       ,     )

      # MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a
      # ~1 difference, it's therefore not a good idea to measure using addition.
      # Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the
      # result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE
      lowercase_	    =       torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE)
      lowercase_	    =       torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE)

      self.assertTrue(lower_bound and upper_bound)



import argparse
import os
import re

import tensorflow as tf
import torch

from transformers import BertConfig, BertModel
from transformers.utils import logging


logging.set_verbosity_info()
lowercase__       =logging.get_logger(__name__)




def    __UpperCamelCase     (				lowerCAmelCase__							:				Union[str, Any]  ,   lowerCAmelCase__							:				int  ,   lowerCAmelCase__							:				Dict  ):
 __a :  List[str]						=  os.path.abspath(lowerCAmelCase__  )
 logger.info(f"Converting TensorFlow checkpoint from {tf_path}"  )
 # Load weights from TF model
 __a :  Tuple						=  tf.train.list_variables(lowerCAmelCase__  )
 __a :  Optional[Any]						=  []
 __a :  Union[str, Any]						=  []
 __a :  str						=  []
 for full_name, shape in init_vars:
  # logger.info(f"Loading TF weight {name} with shape {shape}")
  __a :  Any						=  full_name.split('''/'''  )
  if full_name == "_CHECKPOINTABLE_OBJECT_GRAPH" or name[0] in ["global_step", "save_counter"]:
   logger.info(f"Skipping non-model layer {full_name}"  )
   continue
  if "optimizer" in full_name:
   logger.info(f"Skipping optimization layer {full_name}"  )
   continue
  if name[0] == "model":
   # ignore initial 'model'
   __a :  Any						=  name[1:]
  # figure out how many levels deep the name is
  __a :  List[Any]						=  0
  for _name in name:
   if _name.startswith('''layer_with_weights'''  ):
    depth += 1
   else:
    break
  layer_depth.append(lowerCAmelCase__  )
  # read data
  __a :  Tuple						=  tf.train.load_variable(lowerCAmelCase__  ,   lowerCAmelCase__  )
  names.append('''/'''.join(lowerCAmelCase__  )  )
  arrays.append(lowerCAmelCase__  )
 logger.info(f"Read a total of {len(lowerCAmelCase__  ):,} layers"  )

 # Sanity check
 if len(set(lowerCAmelCase__  )  ) != 1:
  raise ValueError(f"Found layer names with different depths (layer depth {list(set(lowerCAmelCase__  )  )})"  )
 __a :  int						=  list(set(lowerCAmelCase__  )  )[0]
 if layer_depth != 1:
  raise ValueError(
      '''The model contains more than just the embedding/encoder layers. This script does not handle MLM/NSP'''
      ''' heads.'''  )

 # convert layers
 logger.info('''Converting weights...'''  )
 for full_name, array in zip(lowerCAmelCase__  ,   lowerCAmelCase__  ):
  __a :  int						=  full_name.split('''/'''  )
  __a :  Tuple						=  model
  __a :  Dict						=  []
  for i, m_name in enumerate(lowerCAmelCase__  ):
   if m_name == ".ATTRIBUTES":
    # variable names end with .ATTRIBUTES/VARIABLE_VALUE
    break
   if m_name.startswith('''layer_with_weights'''  ):
    __a :  Union[str, Any]						=  int(m_name.split('''-'''  )[-1]  )
    if layer_num <= 2:
     # embedding layers
     # layer_num 0: word_embeddings
     # layer_num 1: position_embeddings
     # layer_num 2: token_type_embeddings
     continue
    elif layer_num == 3:
     # embedding LayerNorm
     trace.extend(['''embeddings''', '''LayerNorm''']  )
     __a :  Union[str, Any]						=  getattr(lowerCAmelCase__  ,   '''embeddings'''  )
     __a :  List[str]						=  getattr(lowerCAmelCase__  ,   '''LayerNorm'''  )
    elif layer_num > 3 and layer_num < config.num_hidden_layers + 4:
     # encoder layers
     trace.extend(['''encoder''', '''layer''', str(layer_num - 4  )]  )
     __a :  Dict						=  getattr(lowerCAmelCase__  ,   '''encoder'''  )
     __a :  Union[str, Any]						=  getattr(lowerCAmelCase__  ,   '''layer'''  )
     __a :  Any						=  pointer[layer_num - 4]
    elif layer_num == config.num_hidden_layers + 4:
     # pooler layer
     trace.extend(['''pooler''', '''dense''']  )
     __a :  Any						=  getattr(lowerCAmelCase__  ,   '''pooler'''  )
     __a :  Optional[int]						=  getattr(lowerCAmelCase__  ,   '''dense'''  )
   elif m_name == "embeddings":
    trace.append('''embeddings'''  )
    __a :  int						=  getattr(lowerCAmelCase__  ,   '''embeddings'''  )
    if layer_num == 0:
     trace.append('''word_embeddings'''  )
     __a :  Optional[int]						=  getattr(lowerCAmelCase__  ,   '''word_embeddings'''  )
    elif layer_num == 1:
     trace.append('''position_embeddings'''  )
     __a :  List[str]						=  getattr(lowerCAmelCase__  ,   '''position_embeddings'''  )
    elif layer_num == 2:
     trace.append('''token_type_embeddings'''  )
     __a :  Optional[Any]						=  getattr(lowerCAmelCase__  ,   '''token_type_embeddings'''  )
    else:
     raise ValueError(f"Unknown embedding layer with name {full_name}"  )
    trace.append('''weight'''  )
    __a :  Tuple						=  getattr(lowerCAmelCase__  ,   '''weight'''  )
   elif m_name == "_attention_layer":
    # self-attention layer
    trace.extend(['''attention''', '''self''']  )
    __a :  Optional[Any]						=  getattr(lowerCAmelCase__  ,   '''attention'''  )
    __a :  Union[str, Any]						=  getattr(lowerCAmelCase__  ,   '''self'''  )
   elif m_name == "_attention_layer_norm":
    # output attention norm
    trace.extend(['''attention''', '''output''', '''LayerNorm''']  )
    __a :  int						=  getattr(lowerCAmelCase__  ,   '''attention'''  )
    __a :  List[Any]						=  getattr(lowerCAmelCase__  ,   '''output'''  )
    __a :  List[Any]						=  getattr(lowerCAmelCase__  ,   '''LayerNorm'''  )
   elif m_name == "_attention_output_dense":
    # output attention dense
    trace.extend(['''attention''', '''output''', '''dense''']  )
    __a :  Optional[int]						=  getattr(lowerCAmelCase__  ,   '''attention'''  )
    __a :  Optional[Any]						=  getattr(lowerCAmelCase__  ,   '''output'''  )
    __a :  Any						=  getattr(lowerCAmelCase__  ,   '''dense'''  )
   elif m_name == "_output_dense":
    # output dense
    trace.extend(['''output''', '''dense''']  )
    __a :  Tuple						=  getattr(lowerCAmelCase__  ,   '''output'''  )
    __a :  str						=  getattr(lowerCAmelCase__  ,   '''dense'''  )
   elif m_name == "_output_layer_norm":
    # output dense
    trace.extend(['''output''', '''LayerNorm''']  )
    __a :  int						=  getattr(lowerCAmelCase__  ,   '''output'''  )
    __a :  str						=  getattr(lowerCAmelCase__  ,   '''LayerNorm'''  )
   elif m_name == "_key_dense":
    # attention key
    trace.append('''key'''  )
    __a :  Union[str, Any]						=  getattr(lowerCAmelCase__  ,   '''key'''  )
   elif m_name == "_query_dense":
    # attention query
    trace.append('''query'''  )
    __a :  Union[str, Any]						=  getattr(lowerCAmelCase__  ,   '''query'''  )
   elif m_name == "_value_dense":
    # attention value
    trace.append('''value'''  )
    __a :  Union[str, Any]						=  getattr(lowerCAmelCase__  ,   '''value'''  )
   elif m_name == "_intermediate_dense":
    # attention intermediate dense
    trace.extend(['''intermediate''', '''dense''']  )
    __a :  Optional[Any]						=  getattr(lowerCAmelCase__  ,   '''intermediate'''  )
    __a :  Optional[int]						=  getattr(lowerCAmelCase__  ,   '''dense'''  )
   elif m_name == "_output_layer_norm":
    # output layer norm
    trace.append('''output'''  )
    __a :  int						=  getattr(lowerCAmelCase__  ,   '''output'''  )
   # weights & biases
   elif m_name in ["bias", "beta"]:
    trace.append('''bias'''  )
    __a :  Dict						=  getattr(lowerCAmelCase__  ,   '''bias'''  )
   elif m_name in ["kernel", "gamma"]:
    trace.append('''weight'''  )
    __a :  List[Any]						=  getattr(lowerCAmelCase__  ,   '''weight'''  )
   else:
    logger.warning(f"Ignored {m_name}"  )
        # for certain layers reshape is necessary
  __a :  List[str]						=  '''.'''.join(lowerCAmelCase__  )
  if re.match(R'''(\S+)\.attention\.self\.(key|value|query)\.(bias|weight)'''  ,   lowerCAmelCase__  ) or re.match(
      R'''(\S+)\.attention\.output\.dense\.weight'''  ,   lowerCAmelCase__  ):
   __a :  str						=  array.reshape(pointer.data.shape  )
  if "kernel" in full_name:
   __a :  Optional[Any]						=  array.transpose()
  if pointer.shape == array.shape:
   __a :  str						=  torch.from_numpy(lowerCAmelCase__  )
  else:
   raise ValueError(
       f"Shape mismatch in layer {full_name}: Model expects shape {pointer.shape} but layer contains shape:"
       f" {array.shape}"  )
  logger.info(f"Successfully set variable {full_name} to PyTorch layer {trace}"  )
 return model




def    __UpperCamelCase     (				lowerCAmelCase__							:				Optional[Any]  ,   lowerCAmelCase__							:				Union[str, Any]  ,   lowerCAmelCase__							:				Optional[Any]  ):
 # Instantiate model
 logger.info(f"Loading model based on config from {config_path}..."  )
 __a :  Dict						=  BertConfig.from_json_file(lowerCAmelCase__  )
 __a :  int						=  BertModel(lowerCAmelCase__  )

 # Load weights from checkpoint
 logger.info(f"Loading weights from checkpoint {tf_checkpoint_path}..."  )
 load_tfa_weights_in_bert(lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  )

 # Save pytorch-model
 logger.info(f"Saving PyTorch model to {pytorch_dump_path}..."  )
 torch.save(model.state_dict()  ,   lowerCAmelCase__  )


if __name__ == "__main__":
      lowercase__       =argparse.ArgumentParser()
      parser.add_argument(
          '--tf_checkpoint_path', type=str, required=True, help='Path to the TensorFlow 2.x checkpoint path.'
      )
      parser.add_argument(
          '--bert_config_file',
          type=str,
          required=True,
          help='The config json file corresponding to the BERT model. This specifies the model architecture.',
      )
      parser.add_argument(
          '--pytorch_dump_path',
          type=str,
          required=True,
          help='Path to the output PyTorch model (must include filename).',
      )
      lowercase__       =parser.parse_args()
      convert_tfa_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
