






import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse("3.8"):
							import importlib_metadata
else:
							import importlib.metadata as importlib_metadata




def 				A		(					lowercase__  :  int ,		lowercase__  :  Union[str, Any]=False  )		-> Dict:
	try:
		UpperCamelCase__ :str						=      os.environ[key]
	except KeyError:
		# KEY isn't set, default to `default`.
		UpperCamelCase__ :Dict						=      default
	else:
		# KEY is set, convert it to True or False.
		try:
			UpperCamelCase__ :Any						=      strtobool(lowercase__  )
		except ValueError:
			# More values are supported, but let's keep the message simple.
			raise ValueError(f"""If set, {key} must be yes or no."""  )
	return _value


UpperCamelCase        =				parse_flag_from_env("RUN_SLOW", default=False)
UpperCamelCase        =				parse_flag_from_env("RUN_REMOTE", default=False)
UpperCamelCase        =				parse_flag_from_env("RUN_LOCAL", default=True)
UpperCamelCase        =				parse_flag_from_env("RUN_PACKAGED", default=True)

# Compression
UpperCamelCase        =				pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="test requires lz4")
UpperCamelCase        =				pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="test requires py7zr")
UpperCamelCase        =				pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="test requires zstandard")

# Audio
UpperCamelCase        =				pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec("soundfile") is None or version.parse(importlib_metadata.version("soundfile")) < version.parse("0.12.0"),
    reason="test requires sndfile>=0.12.1: 'pip install \"soundfile>=0.12.1\"'; ",
)

# Beam
UpperCamelCase        =				pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse("0.3.2"),
    reason="test requires apache-beam and a compatible dill version",
)

# Dill-cloudpickle compatibility
UpperCamelCase        =				pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("0.3.2"),
    reason="test requires dill>0.3.2 for cloudpickle compatibility",
)

# Windows
UpperCamelCase        =				pytest.mark.skipif(
    sys.platform == "win32",
    reason="test should not be run on Windows",
)




def 				A		(					lowercase__  :  Any  )		-> List[Any]:
	try:
		import faiss  # noqa
	except ImportError:
		UpperCamelCase__ :Optional[Any]						=      unittest.skip("""test requires faiss"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  List[str]  )		-> List[str]:
	try:
		import regex  # noqa
	except ImportError:
		UpperCamelCase__ :List[str]						=      unittest.skip("""test requires regex"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  int  )		-> List[str]:
	try:
		import elasticsearch  # noqa
	except ImportError:
		UpperCamelCase__ :Tuple						=      unittest.skip("""test requires elasticsearch"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  Dict  )		-> str:
	try:
		import sqlalchemy  # noqa
	except ImportError:
		UpperCamelCase__ :str						=      unittest.skip("""test requires sqlalchemy"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  List[str]  )		-> List[str]:
	if not config.TORCH_AVAILABLE:
		UpperCamelCase__ :Tuple						=      unittest.skip("""test requires PyTorch"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  Dict  )		-> Union[str, Any]:
	if not config.TF_AVAILABLE:
		UpperCamelCase__ :List[str]						=      unittest.skip("""test requires TensorFlow"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  Tuple  )		-> Optional[int]:
	if not config.JAX_AVAILABLE:
		UpperCamelCase__ :str						=      unittest.skip("""test requires JAX"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  List[Any]  )		-> Optional[Any]:
	if not config.PIL_AVAILABLE:
		UpperCamelCase__ :Optional[int]						=      unittest.skip("""test requires Pillow"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  Any  )		-> Any:
	try:
		import transformers  # noqa F401
	except ImportError:
		return unittest.skip("""test requires transformers"""  )(lowercase__  )
	else:
		return test_case




def 				A		(					lowercase__  :  Union[str, Any]  )		-> Any:
	try:
		import tiktoken  # noqa F401
	except ImportError:
		return unittest.skip("""test requires tiktoken"""  )(lowercase__  )
	else:
		return test_case




def 				A		(					lowercase__  :  Optional[Any]  )		-> Union[str, Any]:
	try:
		import spacy  # noqa F401
	except ImportError:
		return unittest.skip("""test requires spacy"""  )(lowercase__  )
	else:
		return test_case




def 				A		(					lowercase__  :  Optional[Any]  )		-> str:

	def _require_spacy_model(lowercase__  :  Tuple  ):
		try:
			import spacy  # noqa F401

			spacy.load(lowercase__  )
		except ImportError:
			return unittest.skip("""test requires spacy"""  )(lowercase__  )
		except OSError:
			return unittest.skip("""test requires spacy model '{}'""".format(lowercase__  )  )(lowercase__  )
		else:
			return test_case

	return _require_spacy_model




def 				A		(					lowercase__  :  int  )		-> List[str]:
	try:
		import pyspark  # noqa F401
	except ImportError:
		return unittest.skip("""test requires pyspark"""  )(lowercase__  )
	else:
		return test_case




def 				A		(					lowercase__  :  Dict  )		-> List[str]:
	try:
		import joblibspark  # noqa F401
	except ImportError:
		return unittest.skip("""test requires joblibspark"""  )(lowercase__  )
	else:
		return test_case




def 				A		(					lowercase__  :  List[str]  )		-> Dict:
	if not _run_slow_tests or _run_slow_tests == 0:
		UpperCamelCase__ :Optional[int]						=      unittest.skip("""test is slow"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  Optional[Any]  )		-> int:
	if not _run_local_tests or _run_local_tests == 0:
		UpperCamelCase__ :Dict						=      unittest.skip("""test is local"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  Optional[Any]  )		-> List[Any]:
	if not _run_packaged_tests or _run_packaged_tests == 0:
		UpperCamelCase__ :str						=      unittest.skip("""test is packaged"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  int  )		-> List[Any]:
	if not _run_remote_tests or _run_remote_tests == 0:
		UpperCamelCase__ :List[Any]						=      unittest.skip("""test requires remote"""  )(lowercase__  )
	return test_case




def 				A		(					*lowercase__  :  List[Any]  )		-> str:
	def decorate(cls  :  Optional[Any]  ):
		for name, fn in cls.__dict__.items():
			if callable(lowercase__  ) and name.startswith("""test"""  ):
				for decorator in decorators:
					UpperCamelCase__ :Any						=      decorator(lowercase__  )
				setattr(cls ,		lowercase__ ,		lowercase__  )
		return cls

	return decorate

class        lowerCAmelCase_				(      lowercase	):







				"""simple docstring"""




				pass

class        lowerCAmelCase_				(      lowercase	):







				"""simple docstring"""




				_snake_case				:   Tuple        =			0
				_snake_case				:   Any        =			1
				_snake_case				:   Union[str, Any]        =			2




@contextmanager
def 				A		(					lowercase__  :  Dict=OfflineSimulationMode.CONNECTION_FAILS ,		lowercase__  :  Tuple=1E-16  )		-> Union[str, Any]:
	UpperCamelCase__ :List[str]						=      requests.Session().request

	def timeout_request(lowercase__  :  str ,		lowercase__  :  Union[str, Any] ,		lowercase__  :  Optional[int] ,		**lowercase__  :  int  ):
		# Change the url to an invalid url so that the connection hangs
		UpperCamelCase__ :Dict						=      """https://10.255.255.1"""
		if kwargs.get("""timeout"""  ) is None:
			raise RequestWouldHangIndefinitelyError(
			    f"""Tried a call to {url} in offline mode with no timeout set. Please set a timeout."""  )
		UpperCamelCase__ :List[str]						=      timeout
		try:
			return online_request(lowercase__ ,		lowercase__ ,		**lowercase__  )
		except Exception as e:
			# The following changes in the error are just here to make the offline timeout error prettier
			UpperCamelCase__ :Optional[int]						=      url
			UpperCamelCase__ :Union[str, Any]						=      e.args[0]
			UpperCamelCase__ :List[Any]						=      (max_retry_error.args[0].replace("""10.255.255.1""" ,		f"""OfflineMock[{url}]"""  ),)
			UpperCamelCase__ :Optional[Any]						=      (max_retry_error,)
			raise

	def raise_connection_error(lowercase__  :  Union[str, Any] ,		lowercase__  :  Tuple ,		**lowercase__  :  Any  ):
		raise requests.ConnectionError("""Offline mode is enabled.""" ,		request=lowercase__  )

	if mode is OfflineSimulationMode.CONNECTION_FAILS:
		with patch("""requests.Session.send""" ,		lowercase__  ):
			yield
	elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
		# inspired from https://stackoverflow.com/a/904609
		with patch("""requests.Session.request""" ,		lowercase__  ):
			yield
	elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
		with patch("""datasets.config.HF_DATASETS_OFFLINE""" ,		lowercase__  ):
			yield
	else:
		raise ValueError("""Please use a value from the OfflineSimulationMode enum."""  )




@contextmanager
def 				A		(					*lowercase__  :  Tuple ,		**lowercase__  :  List[Any]  )		-> Optional[int]:
	UpperCamelCase__ :Any						=      str(Path().resolve()  )
	with tempfile.TemporaryDirectory(*lowercase__ ,		**lowercase__  ) as tmp_dir:
		try:
			os.chdir(lowercase__  )
			yield
		finally:
			os.chdir(lowercase__  )




@contextmanager
def 				A		(					)		-> List[Any]:
	import gc

	gc.collect()
	UpperCamelCase__ :Tuple						=      pa.total_allocated_bytes()
	yield
	assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."




@contextmanager
def 				A		(					)		-> Optional[int]:
	import gc

	gc.collect()
	UpperCamelCase__ :int						=      pa.total_allocated_bytes()
	yield
	assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."




def 				A		(					lowercase__  :  List[str] ,		lowercase__  :  List[str]  )		-> str:
	return deepcopy(lowercase__  ).integers(0 ,		100 ,		10  ).tolist() == deepcopy(lowercase__  ).integers(0 ,		100 ,		10  ).tolist()




def 				A		(					lowercase__  :  str  )		-> Union[str, Any]:
	import decorator
	from requests.exceptions import HTTPError

	def _wrapper(lowercase__  :  int ,		*lowercase__  :  str ,		**lowercase__  :  Optional[int]  ):
		try:
			return func(*lowercase__ ,		**lowercase__  )
		except HTTPError as err:
			if str(lowercase__  ).startswith("""500"""  ) or str(lowercase__  ).startswith("""502"""  ):
				pytest.xfail(str(lowercase__  )  )
			raise err

	return decorator.decorator(_wrapper ,		lowercase__  )

class        lowerCAmelCase_				:







				"""simple docstring"""




				def __init__( self     :Optional[Any]  ,     lowerCamelCase__     :int  ,     lowerCamelCase__     :Tuple  ,     lowerCamelCase__     :Union[str, Any]     ):
					UpperCamelCase__ :Union[str, Any]						=      returncode
					UpperCamelCase__ :Tuple						=      stdout
					UpperCamelCase__ :List[Any]						=      stderr




async def 				A		(					lowercase__  :  Union[str, Any] ,		lowercase__  :  List[Any]  )		-> Dict:
	while True:
		UpperCamelCase__ :str						=      await stream.readline()
		if line:
			callback(lowercase__  )
		else:
			break




async def 				A		(					lowercase__  :  Optional[Any] ,		lowercase__  :  Tuple=None ,		lowercase__  :  Union[str, Any]=None ,		lowercase__  :  Dict=None ,		lowercase__  :  Optional[Any]=False ,		lowercase__  :  List[Any]=False  )		-> _RunOutput:
	if echo:
		print("""\nRunning: """ ,		""" """.join(lowercase__  )  )

	UpperCamelCase__ :int						=      await asyncio.create_subprocess_exec(
	    cmd[0] ,		*cmd[1:] ,		stdin=lowercase__ ,		stdout=asyncio.subprocess.PIPE ,		stderr=asyncio.subprocess.PIPE ,		env=lowercase__ ,		)

	# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
	# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
	#
	# If it starts hanging, will need to switch to the following code. The problem is that no data
	# will be seen until it's done and if it hangs for example there will be no debug info.
	# out, err = await p.communicate()
	# return _RunOutput(p.returncode, out, err)

	UpperCamelCase__ :Dict						=      []
	UpperCamelCase__ :int						=      []

	def tee(lowercase__  :  int ,		lowercase__  :  List[str] ,		lowercase__  :  Any ,		lowercase__  :  Tuple=""  ):
		UpperCamelCase__ :int						=      line.decode("""utf-8"""  ).rstrip()
		sink.append(lowercase__  )
		if not quiet:
			print(lowercase__ ,		lowercase__ ,		file=lowercase__  )

    # XXX: the timeout doesn't seem to make any difference here
	await asyncio.wait(
	    [
	        _read_stream(p.stdout ,		lambda lowercase__  : tee(lowercase__ ,		lowercase__ ,		sys.stdout ,		label="""stdout:"""  )  ),
	        _read_stream(p.stderr ,		lambda lowercase__  : tee(lowercase__ ,		lowercase__ ,		sys.stderr ,		label="""stderr:"""  )  ),
	    ] ,		timeout=lowercase__ ,		)
	return _RunOutput(await p.wait() ,		lowercase__ ,		lowercase__  )




def 				A		(					lowercase__  :  Tuple ,		lowercase__  :  Optional[Any]=None ,		lowercase__  :  Optional[Any]=None ,		lowercase__  :  List[str]=180 ,		lowercase__  :  Any=False ,		lowercase__  :  Optional[Any]=True  )		-> _RunOutput:
	UpperCamelCase__ :Optional[Any]						=      asyncio.get_event_loop()
	UpperCamelCase__ :Optional[int]						=      loop.run_until_complete(
	    _stream_subprocess(lowercase__ ,		env=lowercase__ ,		stdin=lowercase__ ,		timeout=lowercase__ ,		quiet=lowercase__ ,		echo=lowercase__  )  )

	UpperCamelCase__ :Tuple						=      """ """.join(lowercase__  )
	if result.returncode > 0:
		UpperCamelCase__ :str						=      """\n""".join(result.stderr  )
		raise RuntimeError(
		    f"""'{cmd_str}' failed with returncode {result.returncode}\n\n"""
		    f"""The combined stderr from workers follows:\n{stderr}"""  )

	# check that the subprocess actually did run and produced some output, should the test rely on
	# the remote side to do the testing
	if not result.stdout and not result.stderr:
		raise RuntimeError(f"""'{cmd_str}' produced no output."""  )

	return result




def 				A		(					)		-> Optional[int]:
	UpperCamelCase__ :str						=      os.environ.get("""PYTEST_XDIST_WORKER""" ,		"""gw0"""  )
	UpperCamelCase__ :Tuple						=      re.sub(r"""^gw""" ,		"""""" ,		lowercase__ ,		0 ,		re.M  )
	return int(lowercase__  )




def 				A		(					)		-> str:
	UpperCamelCase__ :Optional[Any]						=      2_9500
	UpperCamelCase__ :List[str]						=      pytest_xdist_worker_id()
	return port + uniq_delta

"""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()
_lowercase							=				logging.get_logger(__name__)



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

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

			# Load weights from checkpoint
			logger.info(F'''Loading weights from checkpoint {tf_checkpoint_path}...'''      )
			load_tfa_weights_in_bert(__magic_name__			,   __magic_name__			,   __magic_name__      )

			# Save pytorch-model
			logger.info(F'''Saving PyTorch model to {pytorch_dump_path}...'''      )
			torch.save(model.state_dict()			,   __magic_name__      )


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)





