


"""simple docstring"""





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()
lowerCamelCase       	=						logging.get_logger(__name__)
def        a__     (				lowerCAmelCase__     ,      lowerCAmelCase__     ,      lowerCAmelCase__				):
      UpperCAmelCase_      			=							os.path.abspath(_UpperCamelCase				)
      logger.info(f"""Converting TensorFlow checkpoint from {tf_path}"""				)
      # Load weights from TF model
      UpperCAmelCase_      			=							tf.train.list_variables(_UpperCamelCase				)
      UpperCAmelCase_      			=							[]
      UpperCAmelCase_      			=							[]
      UpperCAmelCase_      			=							[]
      for full_name, shape in init_vars:
            # logger.info(f"Loading TF weight {name} with shape {shape}")
            UpperCAmelCase_      			=							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'
                  UpperCAmelCase_      			=							name[1:]
            # figure out how many levels deep the name is
            UpperCAmelCase_      			=							0
            for _name in name:
                  if _name.startswith("layer_with_weights"				):
                        depth += 1
                  else:
                        break
            layer_depth.append(_UpperCamelCase				)
            # read data
            UpperCAmelCase_      			=							tf.train.load_variable(_UpperCamelCase     ,      _UpperCamelCase				)
            names.append("/".join(_UpperCamelCase				)				)
            arrays.append(_UpperCamelCase				)
      logger.info(f"""Read a total of {len(_UpperCamelCase				):,} layers"""				)

      # Sanity check
      if len(set(_UpperCamelCase				)				) != 1:
            raise ValueError(f"""Found layer names with different depths (layer depth {list(set(_UpperCamelCase				)				)})"""				)
      UpperCAmelCase_      			=							list(set(_UpperCamelCase				)				)[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(_UpperCamelCase     ,      _UpperCamelCase				):
            UpperCAmelCase_      			=							full_name.split("/"				)
            UpperCAmelCase_      			=							model
            UpperCAmelCase_      			=							[]
            for i, m_name in enumerate(_UpperCamelCase				):
                  if m_name == ".ATTRIBUTES":
                        # variable names end with .ATTRIBUTES/VARIABLE_VALUE
                        break
                  if m_name.startswith("layer_with_weights"				):
                        UpperCAmelCase_      			=							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"]				)
                              UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "embeddings"				)
                              UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "LayerNorm"				)
                        elif layer_num > 3 and layer_num < config.num_hidden_layers + 4:
                              # encoder layers
                              trace.extend(["encoder", "layer", str(layer_num - 4				)]				)
                              UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "encoder"				)
                              UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "layer"				)
                              UpperCAmelCase_      			=							pointer[layer_num - 4]
                        elif layer_num == config.num_hidden_layers + 4:
                              # pooler layer
                              trace.extend(["pooler", "dense"]				)
                              UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "pooler"				)
                              UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "dense"				)
                  elif m_name == "embeddings":
                        trace.append("embeddings"				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "embeddings"				)
                        if layer_num == 0:
                              trace.append("word_embeddings"				)
                              UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "word_embeddings"				)
                        elif layer_num == 1:
                              trace.append("position_embeddings"				)
                              UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "position_embeddings"				)
                        elif layer_num == 2:
                              trace.append("token_type_embeddings"				)
                              UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "token_type_embeddings"				)
                        else:
                              raise ValueError(f"""Unknown embedding layer with name {full_name}"""				)
                        trace.append("weight"				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "weight"				)
                  elif m_name == "_attention_layer":
                        # self-attention layer
                        trace.extend(["attention", "self"]				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "attention"				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "self"				)
                  elif m_name == "_attention_layer_norm":
                        # output attention norm
                        trace.extend(["attention", "output", "LayerNorm"]				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "attention"				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "output"				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "LayerNorm"				)
                  elif m_name == "_attention_output_dense":
                        # output attention dense
                        trace.extend(["attention", "output", "dense"]				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "attention"				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "output"				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "dense"				)
                  elif m_name == "_output_dense":
                        # output dense
                        trace.extend(["output", "dense"]				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "output"				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "dense"				)
                  elif m_name == "_output_layer_norm":
                        # output dense
                        trace.extend(["output", "LayerNorm"]				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "output"				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "LayerNorm"				)
                  elif m_name == "_key_dense":
                        # attention key
                        trace.append("key"				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "key"				)
                  elif m_name == "_query_dense":
                        # attention query
                        trace.append("query"				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "query"				)
                  elif m_name == "_value_dense":
                        # attention value
                        trace.append("value"				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "value"				)
                  elif m_name == "_intermediate_dense":
                        # attention intermediate dense
                        trace.extend(["intermediate", "dense"]				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "intermediate"				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "dense"				)
                  elif m_name == "_output_layer_norm":
                        # output layer norm
                        trace.append("output"				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "output"				)
                  # weights & biases
                  elif m_name in ["bias", "beta"]:
                        trace.append("bias"				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "bias"				)
                  elif m_name in ["kernel", "gamma"]:
                        trace.append("weight"				)
                        UpperCAmelCase_      			=							getattr(_UpperCamelCase     ,      "weight"				)
                  else:
                        logger.warning(f"""Ignored {m_name}"""				)
        # for certain layers reshape is necessary
            UpperCAmelCase_      			=							".".join(_UpperCamelCase				)
            if re.match(r"(\S+)\.attention\.self\.(key|value|query)\.(bias|weight)"     ,      _UpperCamelCase				) or re.match(
                r"(\S+)\.attention\.output\.dense\.weight"     ,      _UpperCamelCase				):
                  UpperCAmelCase_      			=							array.reshape(pointer.data.shape				)
            if "kernel" in full_name:
                  UpperCAmelCase_      			=							array.transpose()
            if pointer.shape == array.shape:
                  UpperCAmelCase_      			=							torch.from_numpy(_UpperCamelCase				)
            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        a__     (				lowerCAmelCase__     ,      lowerCAmelCase__     ,      lowerCAmelCase__				):
      # Instantiate model
      logger.info(f"""Loading model based on config from {config_path}..."""				)
      UpperCAmelCase_      			=							BertConfig.from_json_file(_UpperCamelCase				)
      UpperCAmelCase_      			=							BertModel(_UpperCamelCase				)

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

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


if __name__ == "__main__":
  lowerCamelCase       	=						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).""",
  )
  lowerCamelCase       	=						parser.parse_args()
  convert_tfa_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)









"""simple docstring"""





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


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

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

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


set_seed(42)

lowerCamelCase       	=						{"""base""": """patrickvonplaten/wav2vec2_tiny_random""", """robust""": """patrickvonplaten/wav2vec2_tiny_random_robust"""}

lowerCamelCase       	=						"""zero2"""
lowerCamelCase       	=						"""zero3"""
lowerCamelCase       	=						[ZEROa, ZEROa]
def        a__     (				lowerCAmelCase__     ,      lowerCAmelCase__     ,      lowerCAmelCase__				):
      # customize the test name generator function as we want both params to appear in the sub-test
      # name, as by default it shows only the first param
      UpperCAmelCase_      			=							parameterized.to_safe_name("_".join(str(lowerCAmelCase__				) for x in param.args				)				)
      return f"""{func.__name__}_{param_based_name}"""


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


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







       '''simple docstring'''


       @parameterized.expand(_UpperCAmelCase		,    name_func=_UpperCAmelCase   )
       def 					lowercase__    (							self      :  Dict		,    _UpperCAmelCase      :  int		,    _UpperCAmelCase      :  Any   )			->						Optional[int]:


             '''simple docstring'''




             self.run_and_check(
                 stage=_UpperCAmelCase		,    model=_UpperCAmelCase		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )



       @require_torch_multi_gpu
       @parameterized.expand(_UpperCAmelCase		,    name_func=_UpperCAmelCase   )
       def 					lowercase__    (							self      :  Any		,    _UpperCAmelCase      :  Optional[Any]		,    _UpperCAmelCase      :  str   )			->						Any:


             '''simple docstring'''




             self.run_and_check(
                 stage=_UpperCAmelCase		,    model=_UpperCAmelCase		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )



       @parameterized.expand(_UpperCAmelCase		,    name_func=_UpperCAmelCase   )
       def 					lowercase__    (							self      :  Optional[int]		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  List[str]   )			->						Union[str, Any]:


             '''simple docstring'''




             self.run_and_check(
                 stage=_UpperCAmelCase		,    model=_UpperCAmelCase		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )



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


             '''simple docstring'''




             self.run_and_check(
                 stage=_UpperCAmelCase		,    model=_UpperCAmelCase		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )



       def 					lowercase__    (							self      :  Optional[Any]		,    _UpperCAmelCase      :  Tuple   )			->						Optional[int]:


             '''simple docstring'''




             pass



       def 					lowercase__    (							self      :  Optional[Any]		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  int = 10		,    _UpperCAmelCase      :  bool = True		,    _UpperCAmelCase      :  bool = True		,    _UpperCAmelCase      :  bool = True		,    )			->						Optional[Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							models[model]

             UpperCAmelCase_      			=							self.run_trainer(
                 stage=_UpperCAmelCase		,    model_name=_UpperCAmelCase		,    eval_steps=_UpperCAmelCase		,    num_train_epochs=1		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )

             self.do_checks(_UpperCAmelCase   )

             return output_dir



       def 					lowercase__    (							self      :  Union[str, Any]		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  int = 10		,    _UpperCAmelCase      :  int = 1		,    _UpperCAmelCase      :  bool = True		,    _UpperCAmelCase      :  bool = True		,    )			->						Tuple:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.get_auto_remove_tmp_dir("./xxx"		,    after=_UpperCAmelCase   )
             UpperCAmelCase_      			=							F"""
            --model_name_or_path {model_name}
            --dataset_name hf-internal-testing/librispeech_asr_dummy
            --dataset_config_name clean
            --train_split_name validation
            --validation_split_name validation
            --output_dir {output_dir}
            --num_train_epochs {str(_UpperCAmelCase   )}
            --per_device_train_batch_size 2
            --per_device_eval_batch_size 2
            --evaluation_strategy steps
            --learning_rate 5e-4
            --warmup_steps 8
            --orthography timit
            --preprocessing_num_workers 1
            --group_by_length
            --freeze_feature_extractor
            --report_to none
            --save_steps 0
            --eval_steps {eval_steps}
            --report_to none
        """.split()

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

             # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true,
             # hence the separate config files
             UpperCAmelCase_      			=							F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split()
             UpperCAmelCase_      			=							[F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""]
             UpperCAmelCase_      			=							self.get_launcher(_UpperCAmelCase   )

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

             return output_dir







       def 					lowercase__    (							self      :  List[Any]		,    _UpperCAmelCase      :  int=False   )			->						Optional[Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							min(2		,    get_gpu_count()   ) if distributed else 1
             return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()




