



"""simple docstring"""




import inspect
import os

import torch
from transformers import AutoModel
from transformers.testing_utils import mockenv_context
from transformers.trainer_utils import set_seed

import accelerate
from accelerate.accelerator import Accelerator
from accelerate.state import AcceleratorState
from accelerate.test_utils.testing import (
    AccelerateTestCase,
    TempDirTestCase,
    execute_subprocess_async,
    require_cuda,
    require_fsdp,
    require_multi_gpu,
    slow,
)
from accelerate.utils.constants import (
    FSDP_AUTO_WRAP_POLICY,
    FSDP_BACKWARD_PREFETCH,
    FSDP_SHARDING_STRATEGY,
    FSDP_STATE_DICT_TYPE,
)
from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin
from accelerate.utils.other import patch_environment


set_seed(42)

_lowerCAmelCase							:   Dict				=				'bert-base-cased'
_lowerCAmelCase							:   List[str]				=				'fp16'
_lowerCAmelCase							:   Optional[Any]				=				'bf16'
_lowerCAmelCase							:   Dict				=				[FPaa, BFaa]






@require_fsdp
@require_cuda
class       UpperCAmelCase_    (							_SCREAMING_SNAKE_CASE		):



      def 		snake_case_   (	self	:      Optional[int]		):
           super().setUp()

           _UpperCAmelCase     :      Optional[int]														=       dict(
               ACCELERATE_USE_FSDP="true"	,      MASTER_ADDR="localhost"	,      MASTER_PORT="10999"	,      RANK="0"	,      LOCAL_RANK="0"	,      WORLD_SIZE="1"	,      )



      def 		snake_case_   (	self	:      int		):
           from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy

           for i, strategy in enumerate(__snake_case		):
                _UpperCAmelCase     :      List[str]														=       self.dist_env.copy()
                _UpperCAmelCase     :      Optional[Any]														=       f'{i + 1}'
                _UpperCAmelCase     :      int														=       strategy
                with mockenv_context(**__snake_case		):
                     _UpperCAmelCase     :      Tuple														=       FullyShardedDataParallelPlugin()
                     self.assertEqual(fsdp_plugin.sharding_strategy	,      ShardingStrategy(i + 1		)		)



      def 		snake_case_   (	self	:      str		):
           from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch

           for i, prefetch_policy in enumerate(__snake_case		):
                _UpperCAmelCase     :      str														=       self.dist_env.copy()
                _UpperCAmelCase     :      str														=       prefetch_policy
                with mockenv_context(**__snake_case		):
                     _UpperCAmelCase     :      str														=       FullyShardedDataParallelPlugin()
                     if prefetch_policy == "NO_PREFETCH":
                          self.assertIsNone(fsdp_plugin.backward_prefetch		)
                     else:
                          self.assertEqual(fsdp_plugin.backward_prefetch	,      BackwardPrefetch(i + 1		)		)



      def 		snake_case_   (	self	:      Optional[Any]		):
           from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType

           for i, state_dict_type in enumerate(__snake_case		):
                _UpperCAmelCase     :      Union[str, Any]														=       self.dist_env.copy()
                _UpperCAmelCase     :      Tuple														=       state_dict_type
                with mockenv_context(**__snake_case		):
                     _UpperCAmelCase     :      Tuple														=       FullyShardedDataParallelPlugin()
                     self.assertEqual(fsdp_plugin.state_dict_type	,      StateDictType(i + 1		)		)
                     if state_dict_type == "FULL_STATE_DICT":
                          self.assertTrue(fsdp_plugin.state_dict_config.offload_to_cpu		)
                          self.assertTrue(fsdp_plugin.state_dict_config.ranka_only		)



      def 		snake_case_   (	self	:      Any		):
           _UpperCAmelCase     :      Tuple														=       AutoModel.from_pretrained(__snake_case		)
           for policy in FSDP_AUTO_WRAP_POLICY:
                _UpperCAmelCase     :      int														=       self.dist_env.copy()
                _UpperCAmelCase     :      Tuple														=       policy
                if policy == "TRANSFORMER_BASED_WRAP":
                     _UpperCAmelCase     :      Union[str, Any]														=       "BertLayer"
                elif policy == "SIZE_BASED_WRAP":
                     _UpperCAmelCase     :      Any														=       "2000"
                with mockenv_context(**__snake_case		):
                     _UpperCAmelCase     :      str														=       FullyShardedDataParallelPlugin()
                     fsdp_plugin.set_auto_wrap_policy(__snake_case		)
                     if policy == "NO_WRAP":
                          self.assertIsNone(fsdp_plugin.auto_wrap_policy		)
                     else:
                          self.assertIsNotNone(fsdp_plugin.auto_wrap_policy		)

           _UpperCAmelCase     :      Optional[Any]														=       self.dist_env.copy()
           _UpperCAmelCase     :      Any														=       "TRANSFORMER_BASED_WRAP"
           _UpperCAmelCase     :      Optional[int]														=       "T5Layer"
           with mockenv_context(**__snake_case		):
                _UpperCAmelCase     :      int														=       FullyShardedDataParallelPlugin()
                with self.assertRaises(__snake_case		) as cm:
                     fsdp_plugin.set_auto_wrap_policy(__snake_case		)
                self.assertTrue("Could not find the transformer layer class to wrap in the model." in str(cm.exception		)		)

           _UpperCAmelCase     :      str														=       self.dist_env.copy()
           _UpperCAmelCase     :      Any														=       "SIZE_BASED_WRAP"
           _UpperCAmelCase     :      str														=       "0"
           with mockenv_context(**__snake_case		):
                _UpperCAmelCase     :      int														=       FullyShardedDataParallelPlugin()
                fsdp_plugin.set_auto_wrap_policy(__snake_case		)
                self.assertIsNone(fsdp_plugin.auto_wrap_policy		)



      def 		snake_case_   (	self	:      Tuple		):
           from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision
           from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler

           for mp_dtype in dtypes:
                _UpperCAmelCase     :      Tuple														=       self.dist_env.copy()
                _UpperCAmelCase     :      Union[str, Any]														=       mp_dtype
                with mockenv_context(**__snake_case		):
                     _UpperCAmelCase     :      Union[str, Any]														=       Accelerator()
                     if mp_dtype == "fp16":
                          _UpperCAmelCase     :      Dict														=       torch.floataa
                     elif mp_dtype == "bf16":
                          _UpperCAmelCase     :      Optional[int]														=       torch.bfloataa
                     _UpperCAmelCase     :      str														=       MixedPrecision(param_dtype=__snake_case	,      reduce_dtype=__snake_case	,      buffer_dtype=__snake_case		)
                     self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy	,      __snake_case		)
                     if mp_dtype == FPaa:
                          self.assertTrue(isinstance(accelerator.scaler	,      __snake_case		)		)
                     elif mp_dtype == BFaa:
                          self.assertIsNone(accelerator.scaler		)
                     AcceleratorState._reset_state(__snake_case		)



      def 		snake_case_   (	self	:      str		):
           from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload

           for flag in [True, False]:
                _UpperCAmelCase     :      List[Any]														=       self.dist_env.copy()
                _UpperCAmelCase     :      int														=       str(__snake_case		).lower()
                with mockenv_context(**__snake_case		):
                     _UpperCAmelCase     :      Optional[Any]														=       FullyShardedDataParallelPlugin()
                     self.assertEqual(fsdp_plugin.cpu_offload	,      CPUOffload(offload_params=__snake_case		)		)







@require_fsdp
@require_multi_gpu
@slow
class       UpperCAmelCase_    (							_SCREAMING_SNAKE_CASE		):



      def 		snake_case_   (	self	:      Dict		):
           super().setUp()
           _UpperCAmelCase     :      int														=       0.82
           _UpperCAmelCase     :      Optional[int]														=       [
               "fsdp_shard_grad_op_transformer_based_wrap",
               "fsdp_full_shard_transformer_based_wrap",
           ]
           _UpperCAmelCase     :      Optional[Any]														=       {
               "multi_gpu_fp16": 3_2_0_0,
               "fsdp_shard_grad_op_transformer_based_wrap_fp16": 2_0_0_0,
               "fsdp_full_shard_transformer_based_wrap_fp16": 1_9_0_0,
               # Disabling below test as it overwhelms the RAM memory usage
               # on CI self-hosted runner leading to tests getting killed.
               # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500,  # fp16 was leading to indefinite hang
           }
           _UpperCAmelCase     :      Dict														=       1_6_0
           _UpperCAmelCase     :      Any														=       1_6_0

           _UpperCAmelCase     :      str														=       inspect.getfile(accelerate.test_utils		)
           _UpperCAmelCase     :      Optional[int]														=       os.path.sep.join(mod_file.split(os.path.sep		)[:-1] + ["scripts", "external_deps"]		)



      def 		snake_case_   (	self	:      Union[str, Any]		):
           _UpperCAmelCase     :      Any														=       os.path.join(self.test_scripts_folder	,      "test_performance.py"		)
           _UpperCAmelCase     :      Union[str, Any]														=       ["accelerate", "launch", "--num_processes=2", "--num_machines=1", "--machine_rank=0", "--use_fsdp"]
           for config in self.performance_configs:
                _UpperCAmelCase     :      Any														=       cmd.copy()
                for i, strategy in enumerate(__snake_case		):
                     if strategy.lower() in config:
                          cmd_config.append(f'--fsdp_sharding_strategy={i+1}'		)
                          break

                if "fp32" in config:
                     cmd_config.append("--mixed_precision=no"		)
                else:
                     cmd_config.append("--mixed_precision=fp16"		)

                if "cpu_offload" in config:
                     cmd_config.append("--fsdp_offload_params=True"		)

                for policy in FSDP_AUTO_WRAP_POLICY:
                     if policy.lower() in config:
                          cmd_config.append(f'--fsdp_auto_wrap_policy={policy}'		)
                          break

                if policy == "TRANSFORMER_BASED_WRAP":
                     cmd_config.append("--fsdp_transformer_layer_cls_to_wrap=BertLayer"		)
                elif policy == "SIZE_BASED_WRAP":
                     cmd_config.append("--fsdp_min_num_params=2000"		)

                cmd_config.extend(
                    [
                        self.test_file_path,
                        f'--output_dir={self.tmpdir}',
                        f'--performance_lower_bound={self.performance_lower_bound}',
                    ]		)
                with patch_environment(omp_num_threads=1		):
                     execute_subprocess_async(__snake_case	,      env=os.environ.copy()		)



      def 		snake_case_   (	self	:      Optional[Any]		):
           _UpperCAmelCase     :      List[str]														=       os.path.join(self.test_scripts_folder	,      "test_checkpointing.py"		)
           _UpperCAmelCase     :      Tuple														=       [
               "accelerate",
               "launch",
               "--num_processes=2",
               "--num_machines=1",
               "--machine_rank=0",
               "--use_fsdp",
               "--mixed_precision=fp16",
               "--fsdp_transformer_layer_cls_to_wrap=BertLayer",
           ]

           for i, strategy in enumerate(__snake_case		):
                _UpperCAmelCase     :      str														=       cmd.copy()
                cmd_config.append(f'--fsdp_sharding_strategy={i+1}'		)
                if strategy != "FULL_SHARD":
                     continue
                _UpperCAmelCase     :      Union[str, Any]														=       len(__snake_case		)
                for state_dict_type in FSDP_STATE_DICT_TYPE:
                     _UpperCAmelCase     :      int														=       cmd_config[:state_dict_config_index]
                     cmd_config.append(f'--fsdp_state_dict_type={state_dict_type}'		)
                     cmd_config.extend(
                         [
                             self.test_file_path,
                             f'--output_dir={self.tmpdir}',
                             "--partial_train_epoch=1",
                         ]		)
                     with patch_environment(omp_num_threads=1		):
                          execute_subprocess_async(__snake_case	,      env=os.environ.copy()		)

                     _UpperCAmelCase     :      Optional[Any]														=       cmd_config[:-1]
                     _UpperCAmelCase     :      List[Any]														=       os.path.join(self.tmpdir	,      "epoch_0"		)
                     cmd_config.extend(
                         [
                             f'--resume_from_checkpoint={resume_from_checkpoint}',
                         ]		)
                     with patch_environment(omp_num_threads=1		):
                          execute_subprocess_async(__snake_case	,      env=os.environ.copy()		)



      def 		snake_case_   (	self	:      str		):
           _UpperCAmelCase     :      Optional[int]														=       os.path.join(self.test_scripts_folder	,      "test_peak_memory_usage.py"		)
           _UpperCAmelCase     :      Optional[Any]														=       [
               "accelerate",
               "launch",
               "--num_processes=2",
               "--num_machines=1",
               "--machine_rank=0",
           ]
           for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items():
                _UpperCAmelCase     :      Dict														=       cmd.copy()
                if "fp16" in spec:
                     cmd_config.extend(["--mixed_precision=fp16"]		)
                else:
                     cmd_config.extend(["--mixed_precision=no"]		)

                if "multi_gpu" in spec:
                     continue
                else:
                     cmd_config.extend(["--use_fsdp"]		)
                     for i, strategy in enumerate(__snake_case		):
                          if strategy.lower() in spec:
                               cmd_config.append(f'--fsdp_sharding_strategy={i+1}'		)
                               break

                     if "cpu_offload" in spec:
                          cmd_config.append("--fsdp_offload_params=True"		)

                     for policy in FSDP_AUTO_WRAP_POLICY:
                          if policy.lower() in spec:
                               cmd_config.append(f'--fsdp_auto_wrap_policy={policy}'		)
                               break

                     if policy == "TRANSFORMER_BASED_WRAP":
                          cmd_config.append("--fsdp_transformer_layer_cls_to_wrap=BertLayer"		)
                     elif policy == "SIZE_BASED_WRAP":
                          cmd_config.append("--fsdp_min_num_params=2000"		)

                cmd_config.extend(
                    [
                        self.test_file_path,
                        f'--output_dir={self.tmpdir}',
                        f'--peak_memory_upper_bound={peak_mem_upper_bound}',
                        f'--n_train={self.n_train}',
                        f'--n_val={self.n_val}',
                    ]		)
                with patch_environment(omp_num_threads=1		):
                     execute_subprocess_async(__snake_case	,      env=os.environ.copy()		)







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()
a__      :     Any         =		logging.get_logger(__name__)

a__      :     Tuple         =		'Hello, World!'
a__      :     Any         =		'en_XX'

def      UpperCAmelCase_    (    _UpperCAmelCase							:str  ,						_UpperCAmelCase							:str  ,						_UpperCAmelCase							:bool				)	->				Optional[Any]:
     '''simple docstring'''


     A_          =       Path('''data_bin'''				)
     A_          =       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				)

     A_          =       xmod.model.encoder.sentence_encoder
     A_          =       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=514  ,						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:
          A_          =       xmod.model.classification_heads['''mnli'''].out_proj.weight.shape[0]

     print('''Our X-MOD config:'''  ,						_UpperCAmelCase				)

     A_          =       XmodForSequenceClassification(_UpperCAmelCase				) if classification_head else XmodForMaskedLM(_UpperCAmelCase				)
     model.eval()

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

     A_          =       xmod_sent_encoder.layernorm_embedding.weight
     A_          =       xmod_sent_encoder.layernorm_embedding.bias

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

          # self attention
          A_          =       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.'''				)

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

          # self-attention output
          A_          =       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.'''				)
          A_          =       xmod_layer.self_attn.out_proj.weight
          A_          =       xmod_layer.self_attn.out_proj.bias
          A_          =       xmod_layer.self_attn_layer_norm.weight
          A_          =       xmod_layer.self_attn_layer_norm.bias

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

          # output
          A_          =       layer.output
          if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape:
               raise AssertionError('''Dimensions of feed-forward weights do not match.'''				)
          A_          =       xmod_layer.fca.weight
          A_          =       xmod_layer.fca.bias
          A_          =       xmod_layer.final_layer_norm.weight
          A_          =       xmod_layer.final_layer_norm.bias
          if bert_output.adapter_layer_norm is not None:
               A_          =       xmod_layer.adapter_layer_norm.weight
               A_          =       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():
               A_          =       bert_output.adapter_modules[lang_code]
               A_          =       xmod_layer.adapter_modules[lang_code]
               A_          =       from_adapter.fca.weight
               A_          =       from_adapter.fca.bias
               A_          =       from_adapter.fca.weight
               A_          =       from_adapter.fca.bias

          # end of layer

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

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

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

     A_          =       model(_UpperCAmelCase				)[0]
     if classification_head:
          A_          =       xmod.model.classification_heads['''mnli'''](xmod.extract_features(_UpperCAmelCase				)				)
     else:
          A_          =       xmod.model(_UpperCAmelCase  ,						lang_id=[SAMPLE_LANGUAGE]				)[0]
     print(our_output.shape  ,						their_output.shape				)
     A_          =       torch.max(torch.abs(our_output - their_output				)				).item()
     print(f'max_absolute_diff = {max_absolute_diff}'				)  # ~ 1e-7
     A_          =       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__":
      a__      :     List[str]         =		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.'
      )
      a__      :     Tuple         =		parser.parse_args()
      convert_xmod_checkpoint_to_pytorch(
          args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
      )



