
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 		UpperCamelCase__  :
   def __init__(self :					Any					,				snake_case_ :					List[Any]					,				snake_case_ :					int=1_3					,				snake_case_ :					List[str]=1_0					,				snake_case_ :					List[Any]=3					,				snake_case_ :					Optional[int]=2					,				snake_case_ :					Optional[int]=2					,				snake_case_ :					Any=2					,				snake_case_ :					str=True					,				snake_case_ :					Tuple=True					,				snake_case_ :					List[Any]=3_2					,				snake_case_ :					Dict=5					,				snake_case_ :					Any=4					,				snake_case_ :					Union[str, Any]=3_7					,				snake_case_ :					Tuple="gelu"					,				snake_case_ :					Optional[Any]=0.1					,				snake_case_ :					Tuple=0.1					,				snake_case_ :					Union[str, Any]=1_0					,				snake_case_ :					Any=0.02					,				snake_case_ :					str=0.9					,				snake_case_ :					Optional[int]=None					,				):
    __a :  Any						=  parent
    __a :  Any						=  batch_size
    __a :  int						=  image_size
    __a :  List[Any]						=  num_channels
    __a :  Any						=  patch_size
    __a :  Optional[int]						=  tubelet_size
    __a :  Optional[int]						=  num_frames
    __a :  str						=  is_training
    __a :  List[str]						=  use_labels
    __a :  List[Any]						=  hidden_size
    __a :  Union[str, Any]						=  num_hidden_layers
    __a :  Optional[int]						=  num_attention_heads
    __a :  List[Any]						=  intermediate_size
    __a :  Tuple						=  hidden_act
    __a :  Union[str, Any]						=  hidden_dropout_prob
    __a :  int						=  attention_probs_dropout_prob
    __a :  Union[str, Any]						=  type_sequence_label_size
    __a :  int						=  initializer_range
    __a :  str						=  mask_ratio
    __a :  int						=  scope

    # in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame
    __a :  List[str]						=  (image_size // patch_size) ** 2
    __a :  Tuple						=  (num_frames // tubelet_size) * self.num_patches_per_frame

    # use this variable to define bool_masked_pos
    __a :  Optional[int]						=  int(mask_ratio * self.seq_length   )
   def       lowerCAmelCase			(self :					str   ):
    __a :  Optional[int]						=  floats_tensor(
        [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]   )

    __a :  Tuple						=  None
    if self.use_labels:
     __a :  List[str]						=  ids_tensor([self.batch_size]					,				self.type_sequence_label_size   )

    __a :  str						=  self.get_config()

    return config, pixel_values, labels
   def       lowerCAmelCase			(self :					int   ):
    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       lowerCAmelCase			(self :					Tuple					,				snake_case_ :					Union[str, Any]					,				snake_case_ :					Dict					,				snake_case_ :					Any   ):
    __a :  List[str]						=  VideoMAEModel(config=snake_case_   )
    model.to(snake_case_   )
    model.eval()
    __a :  Union[str, Any]						=  model(snake_case_   )
    self.parent.assertEqual(result.last_hidden_state.shape					,				(self.batch_size, self.seq_length, self.hidden_size)   )
   def       lowerCAmelCase			(self :					List[str]					,				snake_case_ :					Dict					,				snake_case_ :					int					,				snake_case_ :					Optional[Any]   ):
    __a :  Optional[int]						=  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
    __a :  Tuple						=  torch.ones((self.num_masks,)   )
    __a :  List[str]						=  torch.cat([mask, torch.zeros(self.seq_length - mask.size(0   )   )]   )
    __a :  Any						=  mask.expand(self.batch_size					,				-1   ).bool()

    __a :  List[Any]						=  model(snake_case_					,				snake_case_   )
    # model only returns predictions for masked patches
    __a :  Dict						=  mask.sum().item()
    __a :  Optional[int]						=  3 * self.tubelet_size * self.patch_size**2
    self.parent.assertEqual(result.logits.shape					,				(self.batch_size, num_masked_patches, decoder_num_labels)   )







   def       lowerCAmelCase			(self :					Optional[int]   ):
    __a :  Tuple						=  self.prepare_config_and_inputs()
    __a				,       __a				,       __a :  Optional[int]						=  config_and_inputs
    __a :  List[Any]						=  {'''pixel_values''': pixel_values}
    return config, inputs_dict





@require_torch
class 		UpperCamelCase__  (       __lowercase    ,__lowercase    ,unittest.TestCase    ):
   _SCREAMING_SNAKE_CASE      :							int	       =      (
       (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else ()
   )
   _SCREAMING_SNAKE_CASE      :							Optional[int]	       =      (
       {"feature-extraction": VideoMAEModel, "video-classification": VideoMAEForVideoClassification}
       if is_torch_available()
       else {}
   )

   _SCREAMING_SNAKE_CASE      :							int	       =      False
   _SCREAMING_SNAKE_CASE      :							Any	       =      False
   _SCREAMING_SNAKE_CASE      :							Dict	       =      False
   _SCREAMING_SNAKE_CASE      :							Any	       =      False
   def       lowerCAmelCase			(self :					List[Any]   ):
    __a :  int						=  VideoMAEModelTester(self   )
    __a :  Union[str, Any]						=  ConfigTester(self					,				config_class=snake_case_					,				has_text_modality=snake_case_					,				hidden_size=3_7   )
   def       lowerCAmelCase			(self :					Dict					,				snake_case_ :					List[Any]					,				snake_case_ :					Optional[Any]					,				snake_case_ :					int=False   ):
    __a :  List[str]						=  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
     __a :  Dict						=  torch.ones((self.model_tester.num_masks,)   )
     __a :  List[str]						=  torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0   )   )]   )
     __a :  List[Any]						=  mask.expand(self.model_tester.batch_size					,				-1   ).bool()
     __a :  Any						=  bool_masked_pos.to(snake_case_   )

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

    return inputs_dict
   def       lowerCAmelCase			(self :					List[Any]   ):
    self.config_tester.run_common_tests()
   @unittest.skip(reason='''VideoMAE does not use inputs_embeds'''   )
   def       lowerCAmelCase			(self :					Optional[int]   ):
    pass
   def       lowerCAmelCase			(self :					Union[str, Any]   ):
    __a				,       __a :  Union[str, Any]						=  self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
     __a :  Dict						=  model_class(snake_case_   )
     self.assertIsInstance(model.get_input_embeddings()					,				(nn.Module)   )
     __a :  Optional[Any]						=  model.get_output_embeddings()
     self.assertTrue(x is None or isinstance(snake_case_					,				nn.Linear   )   )
   def       lowerCAmelCase			(self :					str   ):
    __a				,       __a :  Tuple						=  self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
     __a :  Union[str, Any]						=  model_class(snake_case_   )
     __a :  Optional[int]						=  inspect.signature(model.forward   )
     # signature.parameters is an OrderedDict => so arg_names order is deterministic
     __a :  Optional[int]						=  [*signature.parameters.keys()]

     __a :  List[Any]						=  ['''pixel_values''']
     self.assertListEqual(arg_names[:1]					,				snake_case_   )
   def       lowerCAmelCase			(self :					Optional[int]   ):
    __a :  str						=  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*snake_case_   )
   def       lowerCAmelCase			(self :					Optional[Any]   ):
    __a :  Optional[Any]						=  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_pretraining(*snake_case_   )
   @slow
   def       lowerCAmelCase			(self :					Any   ):
    for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     __a :  Tuple						=  VideoMAEModel.from_pretrained(snake_case_   )
     self.assertIsNotNone(snake_case_   )
   def       lowerCAmelCase			(self :					List[str]   ):
    if not self.has_attentions:
     pass

    else:
     __a				,       __a :  Dict						=  self.model_tester.prepare_config_and_inputs_for_common()
     __a :  List[Any]						=  True

     for model_class in self.all_model_classes:
      __a :  List[Any]						=  self.model_tester.seq_length - self.model_tester.num_masks
      __a :  Any						=  (
          num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length
      )

      __a :  List[Any]						=  True
      __a :  str						=  False
      __a :  Any						=  True
      __a :  List[Any]						=  model_class(snake_case_   )
      model.to(snake_case_   )
      model.eval()
      with torch.no_grad():
       __a :  Tuple						=  model(**self._prepare_for_class(snake_case_					,				snake_case_   )   )
      __a :  Any						=  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"]
      __a :  List[Any]						=  True
      __a :  Dict						=  model_class(snake_case_   )
      model.to(snake_case_   )
      model.eval()
      with torch.no_grad():
       __a :  Tuple						=  model(**self._prepare_for_class(snake_case_					,				snake_case_   )   )
      __a :  List[Any]						=  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]					,				)
      __a :  str						=  len(snake_case_   )

      # Check attention is always last and order is fine
      __a :  Tuple						=  True
      __a :  Any						=  True
      __a :  Optional[int]						=  model_class(snake_case_   )
      model.to(snake_case_   )
      model.eval()
      with torch.no_grad():
       __a :  Tuple						=  model(**self._prepare_for_class(snake_case_					,				snake_case_   )   )

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

      __a :  Dict						=  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       lowerCAmelCase			(self :					Tuple   ):
    def check_hidden_states_output(snake_case_ :					Optional[Any]					,				snake_case_ :					Dict					,				snake_case_ :					Tuple   ):
     __a :  int						=  model_class(snake_case_   )
     model.to(snake_case_   )
     model.eval()

     with torch.no_grad():
      __a :  List[str]						=  model(**self._prepare_for_class(snake_case_					,				snake_case_   )   )

     __a :  Tuple						=  outputs.hidden_states
     __a :  Optional[Any]						=  self.model_tester.num_hidden_layers + 1
     self.assertEqual(len(snake_case_   )					,				snake_case_   )

     __a :  int						=  self.model_tester.seq_length - self.model_tester.num_masks
     __a :  Dict						=  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]					,				)

    __a				,       __a :  str						=  self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
     __a :  int						=  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"]
     __a :  Dict						=  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       lowerCAmelCase			(self :					Optional[int]   ):
    pass





def    __UpperCamelCase     (				):
 __a :  Tuple						=  hf_hub_download(
     repo_id='''hf-internal-testing/spaghetti-video'''  ,   filename='''eating_spaghetti.npy'''  ,   repo_type='''dataset'''  )
 __a :  int						=  np.load(lowerCAmelCase__  )
 return list(lowerCAmelCase__  )



@require_torch
@require_vision
class 		UpperCamelCase__  (       unittest.TestCase    ):
   @cached_property
   def       lowerCAmelCase			(self :					Optional[Any]   ):
    # logits were tested with a different mean and std, so we use the same here
    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       lowerCAmelCase			(self :					List[Any]   ):
    __a :  List[Any]						=  VideoMAEForVideoClassification.from_pretrained('''MCG-NJU/videomae-base-finetuned-kinetics'''   ).to(
        snake_case_   )

    __a :  Union[str, Any]						=  self.default_image_processor
    __a :  Any						=  prepare_video()
    __a :  int						=  image_processor(snake_case_					,				return_tensors='''pt'''   ).to(snake_case_   )

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

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

    __a :  Optional[int]						=  torch.tensor([0.3669, -0.0688, -0.2421]   ).to(snake_case_   )

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







   @slow
   def       lowerCAmelCase			(self :					Dict   ):
    __a :  str						=  VideoMAEForPreTraining.from_pretrained('''MCG-NJU/videomae-base-short'''   ).to(snake_case_   )

    __a :  Optional[Any]						=  self.default_image_processor
    __a :  Optional[Any]						=  prepare_video()
    __a :  Optional[Any]						=  image_processor(snake_case_					,				return_tensors='''pt'''   ).to(snake_case_   )

    # add boolean mask, indicating which patches to mask
    __a :  int						=  hf_hub_download(repo_id='''hf-internal-testing/bool-masked-pos'''					,				filename='''bool_masked_pos.pt'''   )
    __a :  List[str]						=  torch.load(snake_case_   )

    # forward pass
    with torch.no_grad():
     __a :  Union[str, Any]						=  model(**snake_case_   )

    # verify the logits
    __a :  int						=  torch.Size([1, 1_4_0_8, 1_5_3_6]   )
    __a :  Any						=  torch.tensor(
        [[0.7994, 0.9612, 0.8508], [0.7401, 0.8958, 0.8302], [0.5862, 0.7468, 0.7325]]					,				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`)
    __a :  Tuple						=  torch.tensor([0.5142]					,				device=snake_case_   )
    self.assertTrue(torch.allclose(outputs.loss					,				snake_case_					,				atol=1E-4   )   )

    # verify the loss (`config.norm_pix_loss` = `False`)
    __a :  Union[str, Any]						=  VideoMAEForPreTraining.from_pretrained('''MCG-NJU/videomae-base-short'''					,				norm_pix_loss=snake_case_   ).to(
        snake_case_   )

    with torch.no_grad():
     __a :  Union[str, Any]						=  model(**snake_case_   )

    __a :  List[Any]						=  torch.tensor(torch.tensor([0.6469]   )					,				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)
