



import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)

def      __lowercase(						UpperCAmelCase__ , UpperCAmelCase__=False			):


      """simple docstring"""



      try:
            lowerCamelCase             =		os.environ[key]
      except KeyError:
            # KEY isn't set, default to `default`.
            lowerCamelCase             =		default
      else:
            # KEY is set, convert it to True or False.
            try:
                  lowerCamelCase             =		strtobool(UpperCAmelCase__			)
            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


a_    :  Union[str, Any]						  =		parse_flag_from_env('RUN_SLOW', default=False)

def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      return unittest.skip("Test was skipped"			)(UpperCAmelCase__			)

def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      return unittest.skipUnless(_run_slow_tests , "test is slow"			)(UpperCAmelCase__			)

def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      return unittest.skipUnless(not torch.cuda.is_available() , "test requires only a CPU"			)(UpperCAmelCase__			)

def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      return unittest.skipUnless(torch.cuda.is_available() , "test requires a GPU"			)(UpperCAmelCase__			)

def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      return unittest.skipUnless(is_xpu_available() , "test requires a XPU"			)(UpperCAmelCase__			)

def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      return unittest.skipUnless(is_mps_available() , "test requires a `mps` backend support in `torch`"			)(UpperCAmelCase__			)

def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      return unittest.skipUnless(
          is_transformers_available() and is_datasets_available() , "test requires the Hugging Face suite"			)(UpperCAmelCase__			)

def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      return unittest.skipUnless(is_bnb_available() , "test requires the bitsandbytes library"			)(UpperCAmelCase__			)

def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      return unittest.skipUnless(is_tpu_available() , "test requires TPU"			)(UpperCAmelCase__			)

def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      return unittest.skipUnless(torch.cuda.device_count() == 1 , "test requires a GPU"			)(UpperCAmelCase__			)

def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      return unittest.skipUnless(torch.xpu.device_count() == 1 , "test requires a XPU"			)(UpperCAmelCase__			)

def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      return unittest.skipUnless(torch.cuda.device_count() > 1 , "test requires multiple GPUs"			)(UpperCAmelCase__			)

def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      return unittest.skipUnless(torch.xpu.device_count() > 1 , "test requires multiple XPUs"			)(UpperCAmelCase__			)

def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      return unittest.skipUnless(is_safetensors_available() , "test requires safetensors"			)(UpperCAmelCase__			)

def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      return unittest.skipUnless(is_deepspeed_available() , "test requires DeepSpeed"			)(UpperCAmelCase__			)

def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      return unittest.skipUnless(is_torch_version(">=" , "1.12.0"			) , "test requires torch version >= 1.12.0"			)(UpperCAmelCase__			)

def      __lowercase(						UpperCAmelCase__=None , UpperCAmelCase__=None			):


      """simple docstring"""



      if test_case is None:
            return partial(UpperCAmelCase__ , version=UpperCAmelCase__			)
      return unittest.skipUnless(is_torch_version(">=" , UpperCAmelCase__			) , F"""test requires torch version >= {version}"""			)(UpperCAmelCase__			)

def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      return unittest.skipUnless(is_tensorboard_available() , "test requires Tensorboard"			)(UpperCAmelCase__			)

def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      return unittest.skipUnless(is_wandb_available() , "test requires wandb"			)(UpperCAmelCase__			)

def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      return unittest.skipUnless(is_comet_ml_available() , "test requires comet_ml"			)(UpperCAmelCase__			)


a_    :  Union[str, Any]						  =		(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)

def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      return unittest.skipUnless(
          _atleast_one_tracker_available , "test requires at least one tracker to be available and for `comet_ml` to not be installed" , )(UpperCAmelCase__			)





class  lowerCamelCase__	(    unittest.TestCase):
     """simple docstring"""



     _A      =      True







     @classmethod
     def     _a   (cls     ):






           '''simple docstring'''



           lowerCamelCase             =		tempfile.mkdtemp()







     @classmethod
     def     _a   (cls     ):






           '''simple docstring'''



           if os.path.exists(cls.tmpdir     ):
                 shutil.rmtree(cls.tmpdir     )







     def     _a   (self     ):






           '''simple docstring'''



           if self.clear_on_setup:
                 for path in Path(self.tmpdir     ).glob("**/*"     ):
                       if path.is_file():
                             path.unlink()
                       elif path.is_dir():
                             shutil.rmtree(__a     )





class  lowerCamelCase__	(    unittest.TestCase):
     """simple docstring"""



     def     _a   (self     ):






           '''simple docstring'''



           super().tearDown()
           # Reset the state of the AcceleratorState singleton.
           AcceleratorState._reset_state()
           PartialState._reset_state()





class  lowerCamelCase__	(    unittest.TestCase):
     """simple docstring"""



     def     _a   (self					,      __a     ):






           '''simple docstring'''



           lowerCamelCase             =		mocks if isinstance(__a					,      (tuple, list)     ) else [mocks]
           for m in self.mocks:
                 m.start()
                 self.addCleanup(m.stop     )



def      __lowercase(						UpperCAmelCase__			):


      """simple docstring"""



      lowerCamelCase             =		AcceleratorState()
      lowerCamelCase             =		tensor[None].clone().to(state.device			)
      lowerCamelCase             =		gather(UpperCAmelCase__			).cpu()
      lowerCamelCase             =		tensor[0].cpu()
      for i in range(tensors.shape[0]			):
            if not torch.equal(tensors[i] , UpperCAmelCase__			):
                  return False
      return True





class  lowerCamelCase__	:
     """simple docstring"""



     def __init__(self					,      __a					,      __a					,      __a     ):






           '''simple docstring'''



           lowerCamelCase             =		returncode
           lowerCamelCase             =		stdout
           lowerCamelCase             =		stderr



async def      __lowercase(						UpperCAmelCase__ , UpperCAmelCase__			):


      """simple docstring"""



      while True:
            lowerCamelCase             =		await stream.readline()
            if line:
                  callback(UpperCAmelCase__			)
            else:
                  break

async def      __lowercase(						UpperCAmelCase__ , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=False , UpperCAmelCase__=False			):


      """simple docstring"""



      if echo:
            print("\nRunning: " , " ".join(UpperCAmelCase__			)			)

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

      # 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)

      lowerCamelCase             =		[]
      lowerCamelCase             =		[]

      def tee(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=""			):
            lowerCamelCase             =		line.decode("utf-8"			).rstrip()
            sink.append(UpperCAmelCase__			)
            if not quiet:
                  print(UpperCAmelCase__ , UpperCAmelCase__ , file=UpperCAmelCase__			)

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

def      __lowercase(						UpperCAmelCase__ , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=180 , UpperCAmelCase__=False , UpperCAmelCase__=True			):


      """simple docstring"""



      lowerCamelCase             =		asyncio.get_event_loop()
      lowerCamelCase             =		loop.run_until_complete(
          _stream_subprocess(UpperCAmelCase__ , env=UpperCAmelCase__ , stdin=UpperCAmelCase__ , timeout=UpperCAmelCase__ , quiet=UpperCAmelCase__ , echo=UpperCAmelCase__			)			)

      lowerCamelCase             =		" ".join(UpperCAmelCase__			)
      if result.returncode > 0:
            lowerCamelCase             =		"\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}"""			)

      return result





class  lowerCamelCase__	(    UpperCAmelCase_):
     """simple docstring"""



     pass



def      __lowercase(						UpperCAmelCase__ , UpperCAmelCase__=False			):


      """simple docstring"""



      try:
            lowerCamelCase             =		subprocess.check_output(UpperCAmelCase__ , stderr=subprocess.STDOUT			)
            if return_stdout:
                  if hasattr(UpperCAmelCase__ , "decode"			):
                        lowerCamelCase             =		output.decode("utf-8"			)
                  return output
      except subprocess.CalledProcessError as e:
            raise SubprocessCallException(
                F"""Command `{" ".join(UpperCAmelCase__			)}` failed with the following error:\n\n{e.output.decode()}"""			) from e




import argparse

import torch

from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert
from transformers.utils import logging


logging.set_verbosity_info()

def      __lowercase(						UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__			):


      """simple docstring"""



      lowerCamelCase             =		MobileBertConfig.from_json_file(UpperCAmelCase__			)
      print(F"""Building PyTorch model from configuration: {config}"""			)
      lowerCamelCase             =		MobileBertForPreTraining(UpperCAmelCase__			)
      # Load weights from tf checkpoint
      lowerCamelCase             =		load_tf_weights_in_mobilebert(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__			)
      # Save pytorch-model
      print(F"""Save PyTorch model to {pytorch_dump_path}"""			)
      torch.save(model.state_dict() , UpperCAmelCase__			)


if __name__ == "__main__":
     a_    :  Any						  =		argparse.ArgumentParser()
     # Required parameters
     parser.add_argument(
         '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.'
     )
     parser.add_argument(
         '--mobilebert_config_file',
         default=None,
         type=str,
         required=True,
         help=(
             'The config json file corresponding to the pre-trained MobileBERT model. \n'
             'This specifies the model architecture.'
         ),
     )
     parser.add_argument(
         '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
     )
     a_    :  List[Any]						  =		parser.parse_args()
     convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.mobilebert_config_file, args.pytorch_dump_path)