





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


snake_case_				=			parse_flag_from_env('RUN_SLOW', default=False)






def lowerCamelCase__    (							snake_case_	:  Tuple       )      ->				List[Any]:
   return unittest.skip('''Test was skipped'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  Union[str, Any]       )      ->				Dict:
   return unittest.skipUnless(_run_slow_tests       ,      '''test is slow'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  str       )      ->				Tuple:
   return unittest.skipUnless(not torch.cuda.is_available()       ,      '''test requires only a CPU'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  Tuple       )      ->				Optional[int]:
   return unittest.skipUnless(torch.cuda.is_available()       ,      '''test requires a GPU'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  str       )      ->				Union[str, Any]:
   return unittest.skipUnless(is_xpu_available()       ,      '''test requires a XPU'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  Dict       )      ->				List[Any]:
   return unittest.skipUnless(is_mps_available()       ,      '''test requires a `mps` backend support in `torch`'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  Union[str, Any]       )      ->				Dict:
   return unittest.skipUnless(
       is_transformers_available() and is_datasets_available()       ,      '''test requires the Hugging Face suite'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  Optional[Any]       )      ->				List[Any]:
   return unittest.skipUnless(is_bnb_available()       ,      '''test requires the bitsandbytes library'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  Tuple       )      ->				Optional[int]:
   return unittest.skipUnless(is_tpu_available()       ,      '''test requires TPU'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  List[Any]       )      ->				Union[str, Any]:
   return unittest.skipUnless(torch.cuda.device_count() == 1       ,      '''test requires a GPU'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  Dict       )      ->				Optional[Any]:
   return unittest.skipUnless(torch.xpu.device_count() == 1       ,      '''test requires a XPU'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  Dict       )      ->				Tuple:
   return unittest.skipUnless(torch.cuda.device_count() > 1       ,      '''test requires multiple GPUs'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  Union[str, Any]       )      ->				Tuple:
   return unittest.skipUnless(torch.xpu.device_count() > 1       ,      '''test requires multiple XPUs'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  List[Any]       )      ->				Dict:
   return unittest.skipUnless(is_safetensors_available()       ,      '''test requires safetensors'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  List[str]       )      ->				Any:
   return unittest.skipUnless(is_deepspeed_available()       ,      '''test requires DeepSpeed'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  Optional[int]       )      ->				Tuple:
   return unittest.skipUnless(is_torch_version('''>='''       ,      '''1.12.0'''       )       ,      '''test requires torch version >= 1.12.0'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  str=None       ,      snake_case_	:  Union[str, Any]=None       )      ->				int:
   if test_case is None:
      return partial(snake_case_       ,      version=snake_case_       )
   return unittest.skipUnless(is_torch_version('''>='''       ,      snake_case_       )       ,      f"""test requires torch version >= {version}"""       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  int       )      ->				Tuple:
   return unittest.skipUnless(is_tensorboard_available()       ,      '''test requires Tensorboard'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  str       )      ->				Optional[Any]:
   return unittest.skipUnless(is_wandb_available()       ,      '''test requires wandb'''       )(snake_case_       )






def lowerCamelCase__    (							snake_case_	:  str       )      ->				Dict:
   return unittest.skipUnless(is_comet_ml_available()       ,      '''test requires comet_ml'''       )(snake_case_       )


snake_case_				=			(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)






def lowerCamelCase__    (							snake_case_	:  int       )      ->				Tuple:
   return unittest.skipUnless(
       _atleast_one_tracker_available       ,      '''test requires at least one tracker to be available and for `comet_ml` to not be installed'''       ,      )(snake_case_       )

class 		SCREAMING_SNAKE_CASE__				(       unittest.TestCase  ):
      A_						:				Optional[Any]							=    True


      @classmethod
      def    a (cls       :      int      ):





         """simple docstring"""



         __snake_case							       =   tempfile.mkdtemp()


      @classmethod
      def    a (cls       :      List[str]      ):





         """simple docstring"""



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


      def    a (self       :      str      ):





         """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 		SCREAMING_SNAKE_CASE__				(       unittest.TestCase  ):


      def    a (self       :      Optional[Any]      ):





         """simple docstring"""



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






class 		SCREAMING_SNAKE_CASE__				(       unittest.TestCase  ):


      def    a (self       :      Optional[int]				,			a__       :      Union[mock.Mock, List[mock.Mock]]      ):





         """simple docstring"""



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






def lowerCamelCase__    (							snake_case_	:  int       )      ->				Dict:
   __snake_case							       =   AcceleratorState()
   __snake_case							       =   tensor[None].clone().to(state.device       )
   __snake_case							       =   gather(snake_case_       ).cpu()
   __snake_case							       =   tensor[0].cpu()
   for i in range(tensors.shape[0]       ):
      if not torch.equal(tensors[i]       ,      snake_case_       ):
         return False
   return True

class 		SCREAMING_SNAKE_CASE__				:


      def __init__(self       :      Tuple				,			a__       :      int				,			a__       :      Dict				,			a__       :      Optional[int]      ):





         """simple docstring"""



         __snake_case							       =   returncode
         __snake_case							       =   stdout
         __snake_case							       =   stderr






async def lowerCamelCase__    (							snake_case_	:  Tuple       ,      snake_case_	:  Tuple       )      ->				Optional[Any]:
   while True:
      __snake_case							       =   await stream.readline()
      if line:
         callback(snake_case_       )
      else:
         break






async def lowerCamelCase__    (							snake_case_	:  List[Any]       ,      snake_case_	:  Union[str, Any]=None       ,      snake_case_	:  Tuple=None       ,      snake_case_	:  Tuple=None       ,      snake_case_	:  int=False       ,      snake_case_	:  Any=False       )      ->				_RunOutput:
   if echo:
      print('''\nRunning: '''       ,      ''' '''.join(snake_case_       )       )

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

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

   __snake_case							       =   []
   __snake_case							       =   []

   def tee(snake_case_	:  Dict       ,      snake_case_	:  str       ,      snake_case_	:  str       ,      snake_case_	:  Dict=""       ):
      __snake_case							       =   line.decode('''utf-8'''       ).rstrip()
      sink.append(snake_case_       )
      if not quiet:
         print(snake_case_       ,      snake_case_       ,      file=snake_case_       )

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






def lowerCamelCase__    (							snake_case_	:  Tuple       ,      snake_case_	:  Union[str, Any]=None       ,      snake_case_	:  Union[str, Any]=None       ,      snake_case_	:  Optional[int]=180       ,      snake_case_	:  Optional[int]=False       ,      snake_case_	:  str=True       )      ->				_RunOutput:
   __snake_case							       =   asyncio.get_event_loop()
   __snake_case							       =   loop.run_until_complete(
       _stream_subprocess(snake_case_       ,      env=snake_case_       ,      stdin=snake_case_       ,      timeout=snake_case_       ,      quiet=snake_case_       ,      echo=snake_case_       )       )

   __snake_case							       =   ''' '''.join(snake_case_       )
   if result.returncode > 0:
      __snake_case							       =   '''\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 		SCREAMING_SNAKE_CASE__				(       _UpperCAmelCase  ):
      pass






def lowerCamelCase__    (							snake_case_	:  List[str]       ,      snake_case_	:  List[str]=False       )      ->				Tuple:
   try:
      __snake_case							       =   subprocess.check_output(snake_case_       ,      stderr=subprocess.STDOUT       )
      if return_stdout:
         if hasattr(snake_case_       ,      '''decode'''       ):
            __snake_case							       =   output.decode('''utf-8'''       )
         return output
   except subprocess.CalledProcessError as e:
      raise SubprocessCallException(
          f"""Command `{' '.join(snake_case_       )}` failed with the following error:\n\n{e.output.decode()}"""       ) from e


import argparse
from pathlib import Path

import fairseq
import torch
from fairseq.models.xmod import XMODModel as FairseqXmodModel
from packaging import version

from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification
from transformers.utils import logging


if version.parse(fairseq.__version__) < version.parse('''0.12.2'''):
   raise Exception('''requires fairseq >= 0.12.2''')
if version.parse(fairseq.__version__) > version.parse('''2'''):
   raise Exception('''requires fairseq < v2''')

logging.set_verbosity_info()
__lowerCamelCase			: Dict							   =		logging.get_logger(__name__)

__lowerCamelCase			: Dict							   =		'''Hello, World!'''
__lowerCamelCase			: Optional[Any]							   =		'''en_XX'''



def 	__SCREAMING_SNAKE_CASE  (					__UpperCamelCase    :       str ,     __UpperCamelCase    :       str ,     __UpperCamelCase    :       bool	)							->					Any:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__										=      Path("""data_bin"""	)
  SCREAMING_SNAKE_CASE__										=      FairseqXmodModel.from_pretrained(
      model_name_or_path=str(Path(__UpperCamelCase	).parent	) ,     checkpoint_file=Path(__UpperCamelCase	).name ,     _name="""xmod_base""" ,     arch="""xmod_base""" ,     task="""multilingual_masked_lm""" ,     data_name_or_path=str(__UpperCamelCase	) ,     bpe="""sentencepiece""" ,     sentencepiece_model=str(Path(__UpperCamelCase	).parent / """sentencepiece.bpe.model"""	) ,     src_dict=str(data_dir / """dict.txt"""	) ,     )
  xmod.eval()  # disable dropout
  print(__UpperCamelCase	)

  SCREAMING_SNAKE_CASE__										=      xmod.model.encoder.sentence_encoder
  SCREAMING_SNAKE_CASE__										=      XmodConfig(
      vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings ,     hidden_size=xmod.cfg.model.encoder_embed_dim ,     num_hidden_layers=xmod.cfg.model.encoder_layers ,     num_attention_heads=xmod.cfg.model.encoder_attention_heads ,     intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim ,     max_position_embeddings=5_14 ,     type_vocab_size=1 ,     layer_norm_eps=1E-5 ,     pre_norm=xmod.cfg.model.encoder_normalize_before ,     adapter_reduction_factor=getattr(xmod.cfg.model ,     """bottleneck""" ,     2	) ,     adapter_layer_norm=xmod.cfg.model.adapter_layer_norm ,     adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm ,     ln_before_adapter=xmod.cfg.model.ln_before_adapter ,     languages=xmod.cfg.model.languages ,     )
  if classification_head:
    SCREAMING_SNAKE_CASE__										=      xmod.model.classification_heads["""mnli"""].out_proj.weight.shape[0]

  print("""Our X-MOD config:""" ,     __UpperCamelCase	)

  SCREAMING_SNAKE_CASE__										=      XmodForSequenceClassification(__UpperCamelCase	) if classification_head else XmodForMaskedLM(__UpperCamelCase	)
  model.eval()

  # Now let's copy all the weights.
  # Embeddings
  SCREAMING_SNAKE_CASE__										=      xmod_sent_encoder.embed_tokens.weight
  SCREAMING_SNAKE_CASE__										=      xmod_sent_encoder.embed_positions.weight
  SCREAMING_SNAKE_CASE__										=      torch.zeros_like(
      model.roberta.embeddings.token_type_embeddings.weight	)  # just zero them out b/c xmod doesn't use them.

  SCREAMING_SNAKE_CASE__										=      xmod_sent_encoder.layernorm_embedding.weight
  SCREAMING_SNAKE_CASE__										=      xmod_sent_encoder.layernorm_embedding.bias

  for i in range(config.num_hidden_layers	):
    # Encoder: start of layer
    SCREAMING_SNAKE_CASE__										=      model.roberta.encoder.layer[i]
    SCREAMING_SNAKE_CASE__										=      xmod_sent_encoder.layers[i]

    # self attention
    SCREAMING_SNAKE_CASE__										=      layer.attention.self
    if not (
        xmod_layer.self_attn.k_proj.weight.data.shape
        == xmod_layer.self_attn.q_proj.weight.data.shape
        == xmod_layer.self_attn.v_proj.weight.data.shape
        == torch.Size((config.hidden_size, config.hidden_size)	)
    ):
      raise AssertionError("""Dimensions of self-attention weights do not match."""	)

    SCREAMING_SNAKE_CASE__										=      xmod_layer.self_attn.q_proj.weight
    SCREAMING_SNAKE_CASE__										=      xmod_layer.self_attn.q_proj.bias
    SCREAMING_SNAKE_CASE__										=      xmod_layer.self_attn.k_proj.weight
    SCREAMING_SNAKE_CASE__										=      xmod_layer.self_attn.k_proj.bias
    SCREAMING_SNAKE_CASE__										=      xmod_layer.self_attn.v_proj.weight
    SCREAMING_SNAKE_CASE__										=      xmod_layer.self_attn.v_proj.bias

    # self-attention output
    SCREAMING_SNAKE_CASE__										=      layer.attention.output
    if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape:
      raise AssertionError("""Dimensions of self-attention output weights do not match."""	)
    SCREAMING_SNAKE_CASE__										=      xmod_layer.self_attn.out_proj.weight
    SCREAMING_SNAKE_CASE__										=      xmod_layer.self_attn.out_proj.bias
    SCREAMING_SNAKE_CASE__										=      xmod_layer.self_attn_layer_norm.weight
    SCREAMING_SNAKE_CASE__										=      xmod_layer.self_attn_layer_norm.bias

    # intermediate
    SCREAMING_SNAKE_CASE__										=      layer.intermediate
    if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape:
      raise AssertionError("""Dimensions of intermediate weights do not match."""	)
    SCREAMING_SNAKE_CASE__										=      xmod_layer.fca.weight
    SCREAMING_SNAKE_CASE__										=      xmod_layer.fca.bias

    # output
    SCREAMING_SNAKE_CASE__										=      layer.output
    if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape:
      raise AssertionError("""Dimensions of feed-forward weights do not match."""	)
    SCREAMING_SNAKE_CASE__										=      xmod_layer.fca.weight
    SCREAMING_SNAKE_CASE__										=      xmod_layer.fca.bias
    SCREAMING_SNAKE_CASE__										=      xmod_layer.final_layer_norm.weight
    SCREAMING_SNAKE_CASE__										=      xmod_layer.final_layer_norm.bias
    if bert_output.adapter_layer_norm is not None:
      SCREAMING_SNAKE_CASE__										=      xmod_layer.adapter_layer_norm.weight
      SCREAMING_SNAKE_CASE__										=      xmod_layer.adapter_layer_norm.bias

    if sorted(bert_output.adapter_modules.keys()	) != sorted(xmod_layer.adapter_modules.keys()	):
      raise AssertionError("""Lists of language adapters do not match."""	)
    for lang_code, adapter in xmod_layer.adapter_modules.items():
      SCREAMING_SNAKE_CASE__										=      bert_output.adapter_modules[lang_code]
      SCREAMING_SNAKE_CASE__										=      xmod_layer.adapter_modules[lang_code]
      SCREAMING_SNAKE_CASE__										=      from_adapter.fca.weight
      SCREAMING_SNAKE_CASE__										=      from_adapter.fca.bias
      SCREAMING_SNAKE_CASE__										=      from_adapter.fca.weight
      SCREAMING_SNAKE_CASE__										=      from_adapter.fca.bias

    # end of layer

  if xmod_sent_encoder.layer_norm is not None:
    SCREAMING_SNAKE_CASE__										=      xmod_sent_encoder.layer_norm.weight
    SCREAMING_SNAKE_CASE__										=      xmod_sent_encoder.layer_norm.bias

  if classification_head:
    SCREAMING_SNAKE_CASE__										=      xmod.model.classification_heads["""mnli"""].dense.weight
    SCREAMING_SNAKE_CASE__										=      xmod.model.classification_heads["""mnli"""].dense.bias
    SCREAMING_SNAKE_CASE__										=      xmod.model.classification_heads["""mnli"""].out_proj.weight
    SCREAMING_SNAKE_CASE__										=      xmod.model.classification_heads["""mnli"""].out_proj.bias
  else:
    # LM Head
    SCREAMING_SNAKE_CASE__										=      xmod.model.encoder.lm_head.dense.weight
    SCREAMING_SNAKE_CASE__										=      xmod.model.encoder.lm_head.dense.bias
    SCREAMING_SNAKE_CASE__										=      xmod.model.encoder.lm_head.layer_norm.weight
    SCREAMING_SNAKE_CASE__										=      xmod.model.encoder.lm_head.layer_norm.bias
    SCREAMING_SNAKE_CASE__										=      xmod.model.encoder.lm_head.weight
    SCREAMING_SNAKE_CASE__										=      xmod.model.encoder.lm_head.bias

  # Let's check that we get the same results.
  SCREAMING_SNAKE_CASE__										=      xmod.encode(__UpperCamelCase	).unsqueeze(0	)  # batch of size 1
  model.roberta.set_default_language(__UpperCamelCase	)

  SCREAMING_SNAKE_CASE__										=      model(__UpperCamelCase	)[0]
  if classification_head:
    SCREAMING_SNAKE_CASE__										=      xmod.model.classification_heads["""mnli"""](xmod.extract_features(__UpperCamelCase	)	)
  else:
    SCREAMING_SNAKE_CASE__										=      xmod.model(__UpperCamelCase ,     lang_id=[SAMPLE_LANGUAGE]	)[0]
  print(our_output.shape ,     their_output.shape	)
  SCREAMING_SNAKE_CASE__										=      torch.max(torch.abs(our_output - their_output	)	).item()
  print(f"""max_absolute_diff = {max_absolute_diff}"""	)  # ~ 1e-7
  SCREAMING_SNAKE_CASE__										=      torch.allclose(__UpperCamelCase ,     __UpperCamelCase ,     atol=1E-3	)
  print("""Do both models output the same tensors?""" ,     """🔥""" if success else """💩"""	)
  if not success:
    raise Exception("""Something went wRoNg"""	)

  Path(__UpperCamelCase	).mkdir(parents=__UpperCamelCase ,     exist_ok=__UpperCamelCase	)
  print(f"""Saving model to {pytorch_dump_folder_path}"""	)
  model.save_pretrained(__UpperCamelCase	)


if __name__ == "__main__":
   __lowerCamelCase			: Dict							   =		argparse.ArgumentParser()
   # Required parameters
   parser.add_argument(
       '''--xmod_checkpoint_path''', default=None, type=str, required=True, help='''Path the official PyTorch dump.'''
   )
   parser.add_argument(
       '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
   )
   parser.add_argument(
       '''--classification_head''', action='''store_true''', help='''Whether to convert a final classification head.'''
   )
   __lowerCamelCase			: str							   =		parser.parse_args()
   convert_xmod_checkpoint_to_pytorch(
       args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
   )
