



"""simple docstring"""
import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import VideoMAEConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
       import torch
       from torch import nn

       from transformers import (
           MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
           VideoMAEForPreTraining,
           VideoMAEForVideoClassification,
           VideoMAEModel,
       )
       from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from transformers import VideoMAEImageProcessor


class       SCREAMING_SNAKE_CASE__       :

    def __init__( self	: Any       ,     lowerCAmelCase_	: List[Any]       ,     lowerCAmelCase_	: int=1_3       ,     lowerCAmelCase_	: List[str]=1_0       ,     lowerCAmelCase_	: List[Any]=3       ,     lowerCAmelCase_	: Optional[int]=2       ,     lowerCAmelCase_	: Optional[int]=2       ,     lowerCAmelCase_	: Any=2       ,     lowerCAmelCase_	: str=True       ,     lowerCAmelCase_	: Tuple=True       ,     lowerCAmelCase_	: List[Any]=3_2       ,     lowerCAmelCase_	: Dict=5       ,     lowerCAmelCase_	: Any=4       ,     lowerCAmelCase_	: Union[str, Any]=3_7       ,     lowerCAmelCase_	: Tuple="gelu"       ,     lowerCAmelCase_	: Optional[Any]=0.1       ,     lowerCAmelCase_	: Tuple=0.1       ,     lowerCAmelCase_	: Union[str, Any]=1_0       ,     lowerCAmelCase_	: Any=0.02       ,     lowerCAmelCase_	: str=0.9       ,     lowerCAmelCase_	: Optional[int]=None       ,     ):







      """simple docstring"""







      lowercase_	    =       parent
      lowercase_	    =       batch_size
      lowercase_	    =       image_size
      lowercase_	    =       num_channels
      lowercase_	    =       patch_size
      lowercase_	    =       tubelet_size
      lowercase_	    =       num_frames
      lowercase_	    =       is_training
      lowercase_	    =       use_labels
      lowercase_	    =       hidden_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_	    =       type_sequence_label_size
      lowercase_	    =       initializer_range
      lowercase_	    =       mask_ratio
      lowercase_	    =       scope

      # in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame
      lowercase_	    =       (image_size // patch_size) ** 2
      lowercase_	    =       (num_frames // tubelet_size) * self.num_patches_per_frame

      # use this variable to define bool_masked_pos
      lowercase_	    =       int(mask_ratio * self.seq_length)

    def     _UpperCAmelCase		( self	: str):







      """simple docstring"""







      lowercase_	    =       floats_tensor(
          [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size])

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

      lowercase_	    =       self.get_config()

      return config, pixel_values, labels

    def     _UpperCAmelCase		( self	: int):







      """simple docstring"""







      return VideoMAEConfig(
          image_size=self.image_size       ,     patch_size=self.patch_size       ,     num_channels=self.num_channels       ,     num_frames=self.num_frames       ,     tubelet_size=self.tubelet_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       ,     is_decoder=snake_case_       ,     initializer_range=self.initializer_range       ,     )

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







      """simple docstring"""







      lowercase_	    =       VideoMAEModel(config=snake_case_)
      model.to(snake_case_)
      model.eval()
      lowercase_	    =       model(snake_case_)
      self.parent.assertEqual(result.last_hidden_state.shape       ,     (self.batch_size, self.seq_length, self.hidden_size))

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







      """simple docstring"""







      lowercase_	    =       VideoMAEForPreTraining(snake_case_)
      model.to(snake_case_)
      model.eval()
      # important: each video needs to have the same number of masked patches
      # hence we define a single mask, which we then repeat for each example in the batch
      lowercase_	    =       torch.ones((self.num_masks,))
      lowercase_	    =       torch.cat([mask, torch.zeros(self.seq_length - mask.size(0))])
      lowercase_	    =       mask.expand(self.batch_size       ,     -1).bool()

      lowercase_	    =       model(snake_case_       ,     snake_case_)
      # model only returns predictions for masked patches
      lowercase_	    =       mask.sum().item()
      lowercase_	    =       3 * self.tubelet_size * self.patch_size**2
      self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, num_masked_patches, decoder_num_labels))




    def     _UpperCAmelCase		( self	: Optional[int]):







      """simple docstring"""







      lowercase_	    =       self.prepare_config_and_inputs()
      lowercase_	    =       config_and_inputs
      lowercase_	    =       {'''pixel_values''': pixel_values}
      return config, inputs_dict







@require_torch
class       SCREAMING_SNAKE_CASE__       (							__lowercase					,     __lowercase					,     unittest.TestCase      ):
    lowercase__          =      (
        (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else ()
    )
    lowercase__          =      (
        {"feature-extraction": VideoMAEModel, "video-classification": VideoMAEForVideoClassification}
        if is_torch_available()
        else {}
    )

    lowercase__          =      False
    lowercase__          =      False
    lowercase__          =      False
    lowercase__          =      False

    def     _UpperCAmelCase		( self	: List[Any]):







      """simple docstring"""







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

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







      """simple docstring"""







      lowercase_	    =       copy.deepcopy(snake_case_)

      if model_class == VideoMAEForPreTraining:
        # important: each video needs to have the same number of masked patches
        # hence we define a single mask, which we then repeat for each example in the batch
        lowercase_	    =       torch.ones((self.model_tester.num_masks,))
        lowercase_	    =       torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0))])
        lowercase_	    =       mask.expand(self.model_tester.batch_size       ,     -1).bool()
        lowercase_	    =       bool_masked_pos.to(snake_case_)

      if return_labels:
        if model_class in [
            *get_values(snake_case_),
        ]:
          lowercase_	    =       torch.zeros(
              self.model_tester.batch_size       ,     dtype=torch.long       ,     device=snake_case_)

      return inputs_dict

    def     _UpperCAmelCase		( self	: List[Any]):







      """simple docstring"""







      self.config_tester.run_common_tests()

    @unittest.skip(reason="""VideoMAE does not use inputs_embeds""")
    def     _UpperCAmelCase		( self	: Optional[int]):







      """simple docstring"""







      pass

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







      """simple docstring"""







      lowercase_	    =       self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        lowercase_	    =       model_class(snake_case_)
        self.assertIsInstance(model.get_input_embeddings()       ,     (nn.Module))
        lowercase_	    =       model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(snake_case_       ,     nn.Linear))

    def     _UpperCAmelCase		( self	: str):







      """simple docstring"""







      lowercase_	    =       self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        lowercase_	    =       model_class(snake_case_)
        lowercase_	    =       inspect.signature(model.forward)
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        lowercase_	    =       [*signature.parameters.keys()]

        lowercase_	    =       ['''pixel_values''']
        self.assertListEqual(arg_names[:1]       ,     snake_case_)

    def     _UpperCAmelCase		( self	: Optional[int]):







      """simple docstring"""







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

    def     _UpperCAmelCase		( self	: Optional[Any]):







      """simple docstring"""







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

    @slow
    def     _UpperCAmelCase		( self	: Any):







      """simple docstring"""







      for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowercase_	    =       VideoMAEModel.from_pretrained(snake_case_)
        self.assertIsNotNone(snake_case_)

    def     _UpperCAmelCase		( self	: List[str]):







      """simple docstring"""







      if not self.has_attentions:
        pass

      else:
        lowercase_	    =       self.model_tester.prepare_config_and_inputs_for_common()
        lowercase_	    =       True

        for model_class in self.all_model_classes:
          lowercase_	    =       self.model_tester.seq_length - self.model_tester.num_masks
          lowercase_	    =       (
              num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length
          )

          lowercase_	    =       True
          lowercase_	    =       False
          lowercase_	    =       True
          lowercase_	    =       model_class(snake_case_)
          model.to(snake_case_)
          model.eval()
          with torch.no_grad():
            lowercase_	    =       model(**self._prepare_for_class(snake_case_       ,     snake_case_))
          lowercase_	    =       outputs.attentions
          self.assertEqual(len(snake_case_)       ,     self.model_tester.num_hidden_layers)

          # check that output_attentions also work using config
          del inputs_dict["output_attentions"]
          lowercase_	    =       True
          lowercase_	    =       model_class(snake_case_)
          model.to(snake_case_)
          model.eval()
          with torch.no_grad():
            lowercase_	    =       model(**self._prepare_for_class(snake_case_       ,     snake_case_))
          lowercase_	    =       outputs.attentions
          self.assertEqual(len(snake_case_)       ,     self.model_tester.num_hidden_layers)

          self.assertListEqual(
              list(attentions[0].shape[-3:])       ,     [self.model_tester.num_attention_heads, seq_len, seq_len]       ,     )
          lowercase_	    =       len(snake_case_)

          # Check attention is always last and order is fine
          lowercase_	    =       True
          lowercase_	    =       True
          lowercase_	    =       model_class(snake_case_)
          model.to(snake_case_)
          model.eval()
          with torch.no_grad():
            lowercase_	    =       model(**self._prepare_for_class(snake_case_       ,     snake_case_))

          self.assertEqual(out_len + 1       ,     len(snake_case_))

          lowercase_	    =       outputs.attentions

          self.assertEqual(len(snake_case_)       ,     self.model_tester.num_hidden_layers)
          self.assertListEqual(
              list(self_attentions[0].shape[-3:])       ,     [self.model_tester.num_attention_heads, seq_len, seq_len]       ,     )

    def     _UpperCAmelCase		( self	: Tuple):







      """simple docstring"""







      def check_hidden_states_output(lowerCAmelCase_	: Optional[Any]       ,     lowerCAmelCase_	: Dict       ,     lowerCAmelCase_	: Tuple):
        lowercase_	    =       model_class(snake_case_)
        model.to(snake_case_)
        model.eval()

        with torch.no_grad():
          lowercase_	    =       model(**self._prepare_for_class(snake_case_       ,     snake_case_))

        lowercase_	    =       outputs.hidden_states
        lowercase_	    =       self.model_tester.num_hidden_layers + 1
        self.assertEqual(len(snake_case_)       ,     snake_case_)

        lowercase_	    =       self.model_tester.seq_length - self.model_tester.num_masks
        lowercase_	    =       num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length

        self.assertListEqual(
            list(hidden_states[0].shape[-2:])       ,     [seq_length, self.model_tester.hidden_size]       ,     )

      lowercase_	    =       self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        lowercase_	    =       True
        check_hidden_states_output(snake_case_       ,     snake_case_       ,     snake_case_)

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        lowercase_	    =       True

        check_hidden_states_output(snake_case_       ,     snake_case_       ,     snake_case_)




    @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""")
    def     _UpperCAmelCase		( self	: Optional[int]):







      """simple docstring"""







      pass







def 	_SCREAMING_SNAKE_CASE  ()       ->  int:







  '''simple docstring'''


  lowercase_	    =       hf_hub_download(
      repo_id="""hf-internal-testing/spaghetti-video"""       ,     filename="""eating_spaghetti.npy"""       ,     repo_type="""dataset"""							)
  lowercase_	    =       np.load(lowerCAmelCase__							)
  return list(lowerCAmelCase__							)


@require_torch
@require_vision
class       SCREAMING_SNAKE_CASE__       (							unittest.TestCase      ):

    @cached_property
    def     _UpperCAmelCase		( self	: Optional[Any]):







      """simple docstring"""







      return (
          VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5]       ,     image_std=[0.5, 0.5, 0.5])
          if is_vision_available()
          else None
      )

    @slow
    def     _UpperCAmelCase		( self	: List[Any]):







      """simple docstring"""







      lowercase_	    =       VideoMAEForVideoClassification.from_pretrained("""MCG-NJU/videomae-base-finetuned-kinetics""").to(
          snake_case_)

      lowercase_	    =       self.default_image_processor
      lowercase_	    =       prepare_video()
      lowercase_	    =       image_processor(snake_case_       ,     return_tensors="""pt""").to(snake_case_)

      # forward pass
      with torch.no_grad():
        lowercase_	    =       model(**snake_case_)

      # verify the logits
      lowercase_	    =       torch.Size((1, 4_0_0))
      self.assertEqual(outputs.logits.shape       ,     snake_case_)

      lowercase_	    =       torch.tensor([0.3_669, -0.0_688, -0.2_421]).to(snake_case_)

      self.assertTrue(torch.allclose(outputs.logits[0, :3]       ,     snake_case_       ,     atol=1E-4))




    @slow
    def     _UpperCAmelCase		( self	: Dict):







      """simple docstring"""







      lowercase_	    =       VideoMAEForPreTraining.from_pretrained("""MCG-NJU/videomae-base-short""").to(snake_case_)

      lowercase_	    =       self.default_image_processor
      lowercase_	    =       prepare_video()
      lowercase_	    =       image_processor(snake_case_       ,     return_tensors="""pt""").to(snake_case_)

      # add boolean mask, indicating which patches to mask
      lowercase_	    =       hf_hub_download(repo_id="""hf-internal-testing/bool-masked-pos"""       ,     filename="""bool_masked_pos.pt""")
      lowercase_	    =       torch.load(snake_case_)

      # forward pass
      with torch.no_grad():
        lowercase_	    =       model(**snake_case_)

      # verify the logits
      lowercase_	    =       torch.Size([1, 1_4_0_8, 1_5_3_6])
      lowercase_	    =       torch.tensor(
          [[0.7_994, 0.9_612, 0.8_508], [0.7_401, 0.8_958, 0.8_302], [0.5_862, 0.7_468, 0.7_325]]       ,     device=snake_case_)
      self.assertEqual(outputs.logits.shape       ,     snake_case_)
      self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]       ,     snake_case_       ,     atol=1E-4))

      # verify the loss (`config.norm_pix_loss` = `True`)
      lowercase_	    =       torch.tensor([0.5_142]       ,     device=snake_case_)
      self.assertTrue(torch.allclose(outputs.loss       ,     snake_case_       ,     atol=1E-4))

      # verify the loss (`config.norm_pix_loss` = `False`)
      lowercase_	    =       VideoMAEForPreTraining.from_pretrained("""MCG-NJU/videomae-base-short"""       ,     norm_pix_loss=snake_case_).to(
          snake_case_)

      with torch.no_grad():
        lowercase_	    =       model(**snake_case_)

      lowercase_	    =       torch.tensor(torch.tensor([0.6_469])       ,     device=snake_case_)
      self.assertTrue(torch.allclose(outputs.loss       ,     snake_case_       ,     atol=1E-4))



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)
