





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

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




@require_fsdp
@require_cuda
class 			UpperCAmelCase					(      snake_case_       ):




      def     lowercase__   (      self      :			List[str]  )    ->				Dict:
            super().setUp()

            _lowerCAmelCase												=							dict(
                ACCELERATE_USE_FSDP="""true"""      ,      MASTER_ADDR="""localhost"""      ,      MASTER_PORT="""10999"""      ,      RANK="""0"""      ,      LOCAL_RANK="""0"""      ,      WORLD_SIZE="""1"""      ,      )




      def     lowercase__   (      self      :			int  )    ->				Tuple:
            from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy

            for i, strategy in enumerate(__snake_case  ):
                  _lowerCAmelCase												=							self.dist_env.copy()
                  _lowerCAmelCase												=							f"{i + 1}"
                  _lowerCAmelCase												=							strategy
                  with mockenv_context(**__snake_case  ):
                        _lowerCAmelCase												=							FullyShardedDataParallelPlugin()
                        self.assertEqual(fsdp_plugin.sharding_strategy      ,      ShardingStrategy(i + 1  )  )




      def     lowercase__   (      self      :			Dict  )    ->				Dict:
            from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch

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




      def     lowercase__   (      self      :			Tuple  )    ->				Tuple:
            from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType

            for i, state_dict_type in enumerate(__snake_case  ):
                  _lowerCAmelCase												=							self.dist_env.copy()
                  _lowerCAmelCase												=							state_dict_type
                  with mockenv_context(**__snake_case  ):
                        _lowerCAmelCase												=							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     lowercase__   (      self      :			Optional[Any]  )    ->				List[Any]:
            _lowerCAmelCase												=							AutoModel.from_pretrained(__snake_case  )
            for policy in FSDP_AUTO_WRAP_POLICY:
                  _lowerCAmelCase												=							self.dist_env.copy()
                  _lowerCAmelCase												=							policy
                  if policy == "TRANSFORMER_BASED_WRAP":
                        _lowerCAmelCase												=							"""BertLayer"""
                  elif policy == "SIZE_BASED_WRAP":
                        _lowerCAmelCase												=							"""2000"""
                  with mockenv_context(**__snake_case  ):
                        _lowerCAmelCase												=							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  )

            _lowerCAmelCase												=							self.dist_env.copy()
            _lowerCAmelCase												=							"""TRANSFORMER_BASED_WRAP"""
            _lowerCAmelCase												=							"""T5Layer"""
            with mockenv_context(**__snake_case  ):
                  _lowerCAmelCase												=							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  )  )

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




      def     lowercase__   (      self      :			Any  )    ->				Any:
            from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision
            from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler

            for mp_dtype in dtypes:
                  _lowerCAmelCase												=							self.dist_env.copy()
                  _lowerCAmelCase												=							mp_dtype
                  with mockenv_context(**__snake_case  ):
                        _lowerCAmelCase												=							Accelerator()
                        if mp_dtype == "fp16":
                              _lowerCAmelCase												=							torch.floataa
                        elif mp_dtype == "bf16":
                              _lowerCAmelCase												=							torch.bfloataa
                        _lowerCAmelCase												=							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     lowercase__   (      self      :			Optional[Any]  )    ->				List[str]:
            from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload

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




@require_fsdp
@require_multi_gpu
@slow
class 			UpperCAmelCase					(      snake_case_       ):




      def     lowercase__   (      self      :			Any  )    ->				List[str]:
            super().setUp()
            _lowerCAmelCase												=							0.82
            _lowerCAmelCase												=							[
                """fsdp_shard_grad_op_transformer_based_wrap""",
                """fsdp_full_shard_transformer_based_wrap""",
            ]
            _lowerCAmelCase												=							{
                """multi_gpu_fp16""": 32_00,
                """fsdp_shard_grad_op_transformer_based_wrap_fp16""": 20_00,
                """fsdp_full_shard_transformer_based_wrap_fp16""": 19_00,
                # 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
            }
            _lowerCAmelCase												=							1_60
            _lowerCAmelCase												=							1_60

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




      def     lowercase__   (      self      :			int  )    ->				str:
            _lowerCAmelCase												=							os.path.join(self.test_scripts_folder      ,      """test_performance.py"""  )
            _lowerCAmelCase												=							["""accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", """--use_fsdp"""]
            for config in self.performance_configs:
                  _lowerCAmelCase												=							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     lowercase__   (      self      :			Any  )    ->				Optional[int]:
            _lowerCAmelCase												=							os.path.join(self.test_scripts_folder      ,      """test_checkpointing.py"""  )
            _lowerCAmelCase												=							[
                """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  ):
                  _lowerCAmelCase												=							cmd.copy()
                  cmd_config.append(f"--fsdp_sharding_strategy={i+1}"  )
                  if strategy != "FULL_SHARD":
                        continue
                  _lowerCAmelCase												=							len(__snake_case  )
                  for state_dict_type in FSDP_STATE_DICT_TYPE:
                        _lowerCAmelCase												=							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()  )

                        _lowerCAmelCase												=							cmd_config[:-1]
                        _lowerCAmelCase												=							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     lowercase__   (      self      :			Optional[Any]  )    ->				Optional[Any]:
            _lowerCAmelCase												=							os.path.join(self.test_scripts_folder      ,      """test_peak_memory_usage.py"""  )
            _lowerCAmelCase												=							[
                """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():
                  _lowerCAmelCase												=							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()  )













'''simple docstring'''






# Usage:
# ./gen-card-facebook-wmt19.py

import os
from pathlib import Path
def        UpperCamelCase__				(		lowerCAmelCase							,     lowerCAmelCase							,     lowerCAmelCase  ):





      """simple docstring"""


      _lowerCAmelCase												=							{
          """en""": """Machine learning is great, isn't it?""",
          """ru""": """Машинное обучение - это здорово, не так ли?""",
          """de""": """Maschinelles Lernen ist großartig, oder?""",
      }

      # BLUE scores as follows:
      # "pair": [fairseq, transformers]
      _lowerCAmelCase												=							{
          """ru-en""": ["""[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)""", """39.20"""],
          """en-ru""": ["""[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)""", """33.47"""],
          """en-de""": ["""[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)""", """42.83"""],
          """de-en""": ["""[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)""", """41.35"""],
      }
      _lowerCAmelCase												=							f"{src_lang}-{tgt_lang}"

      _lowerCAmelCase												=							f"\n---\nlanguage: \n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt19\n- facebook\nlicense: apache-2.0\ndatasets:\n- wmt19\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.\n\nFor more details, please see, [Facebook FAIR's WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).\n\nThe abbreviation FSMT stands for FairSeqMachineTranslation\n\nAll four models are available:\n\n* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)\n* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)\n* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)\n* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = \"facebook/wmt19-{src_lang}-{tgt_lang}\"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = \"{texts[src_lang]}\"\ninput_ids = tokenizer.encode(input, return_tensors=\"pt\")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n- The original (and this ported model) doesn't seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)\n\n## Training data\n\nPretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).\n\n## Eval results\n\npair   | fairseq | transformers\n-------|---------|----------\n{pair}  | {scores[pair][0]} | {scores[pair][1]}\n\nThe score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn't support:\n- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).\n- re-ranking\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=15\nmkdir -p $DATA_DIR\nsacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\nnote: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt19/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)\n\n\n### BibTeX entry and citation info\n\n```bibtex\n@inproceedings{{...,\n  year={{2020}},\n  title={{Facebook FAIR's WMT19 News Translation Task Submission}},\n  author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},\n  booktitle={{Proc. of WMT}},\n}}\n```\n\n\n## TODO\n\n- port model ensemble (fairseq uses 4 model checkpoints)\n\n"
      os.makedirs(lowerCAmelCase							,     exist_ok=lowerCAmelCase  )
      _lowerCAmelCase												=							os.path.join(lowerCAmelCase							,     """README.md"""  )
      print(f"Generating {path}"  )
      with open(lowerCAmelCase							,     """w"""							,     encoding="""utf-8"""  ) as f:
            f.write(lowerCAmelCase  )


# make sure we are under the root of the project
A__    :       Optional[int]              =Path(__file__).resolve().parent.parent.parent
A__    :       Union[str, Any]              =repo_dir / '''model_cards'''

for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]:
      A__       ,						A__       ,						A__    :       Optional[Any]              =model_name.split('''-''')
      A__    :       List[str]              =model_cards_dir / '''facebook''' / model_name
      write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)






