





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 					=      'bert-base-cased'
_lowerCamelCase 					=      'fp16'
_lowerCamelCase 					=      'bf16'
_lowerCamelCase 					=      [FPaa, BFaa]




@require_fsdp
@require_cuda
class 	UpperCamelCase_							(  UpperCamelCase__     ):


							def   _snake_case	(				self     :Optional[Any]		) -> Optional[Any]:



									"""simple docstring"""



									super().setUp()

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


							def   _snake_case	(				self     :List[Any]		) -> Tuple:



									"""simple docstring"""



									from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy

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


							def   _snake_case	(				self     :int		) -> List[str]:



									"""simple docstring"""



									from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch

									for i, prefetch_policy in enumerate(__A		):
											SCREAMING_SNAKE_CASE__								=   self.dist_env.copy()
											SCREAMING_SNAKE_CASE__								=   prefetch_policy
											with mockenv_context(**__A		):
													SCREAMING_SNAKE_CASE__								=   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     :List[str]		) -> List[str]:



									"""simple docstring"""



									from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType

									for i, state_dict_type in enumerate(__A		):
											SCREAMING_SNAKE_CASE__								=   self.dist_env.copy()
											SCREAMING_SNAKE_CASE__								=   state_dict_type
											with mockenv_context(**__A		):
													SCREAMING_SNAKE_CASE__								=   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     :str		) -> str:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   AutoModel.from_pretrained(__A		)
									for policy in FSDP_AUTO_WRAP_POLICY:
											SCREAMING_SNAKE_CASE__								=   self.dist_env.copy()
											SCREAMING_SNAKE_CASE__								=   policy
											if policy == "TRANSFORMER_BASED_WRAP":
													SCREAMING_SNAKE_CASE__								=   """BertLayer"""
											elif policy == "SIZE_BASED_WRAP":
													SCREAMING_SNAKE_CASE__								=   """2000"""
											with mockenv_context(**__A		):
													SCREAMING_SNAKE_CASE__								=   FullyShardedDataParallelPlugin()
													fsdp_plugin.set_auto_wrap_policy(__A		)
													if policy == "NO_WRAP":
															self.assertIsNone(fsdp_plugin.auto_wrap_policy		)
													else:
															self.assertIsNotNone(fsdp_plugin.auto_wrap_policy		)

									SCREAMING_SNAKE_CASE__								=   self.dist_env.copy()
									SCREAMING_SNAKE_CASE__								=   """TRANSFORMER_BASED_WRAP"""
									SCREAMING_SNAKE_CASE__								=   """T5Layer"""
									with mockenv_context(**__A		):
											SCREAMING_SNAKE_CASE__								=   FullyShardedDataParallelPlugin()
											with self.assertRaises(__A		) as cm:
													fsdp_plugin.set_auto_wrap_policy(__A		)
											self.assertTrue("""Could not find the transformer layer class to wrap in the model.""" in str(cm.exception		)		)

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


							def   _snake_case	(				self     :Optional[Any]		) -> Optional[int]:



									"""simple docstring"""



									from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision
									from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler

									for mp_dtype in dtypes:
											SCREAMING_SNAKE_CASE__								=   self.dist_env.copy()
											SCREAMING_SNAKE_CASE__								=   mp_dtype
											with mockenv_context(**__A		):
													SCREAMING_SNAKE_CASE__								=   Accelerator()
													if mp_dtype == "fp16":
															SCREAMING_SNAKE_CASE__								=   torch.floataa
													elif mp_dtype == "bf16":
															SCREAMING_SNAKE_CASE__								=   torch.bfloataa
													SCREAMING_SNAKE_CASE__								=   MixedPrecision(param_dtype=__A				,					reduce_dtype=__A				,					buffer_dtype=__A		)
													self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy				,					__A		)
													if mp_dtype == FPaa:
															self.assertTrue(isinstance(accelerator.scaler				,					__A		)		)
													elif mp_dtype == BFaa:
															self.assertIsNone(accelerator.scaler		)
													AcceleratorState._reset_state(__A		)


							def   _snake_case	(				self     :str		) -> str:



									"""simple docstring"""



									from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload

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




@require_fsdp
@require_multi_gpu
@slow
class 	UpperCamelCase_							(  UpperCamelCase__     ):


							def   _snake_case	(				self     :Any		) -> Any:



									"""simple docstring"""



									super().setUp()
									SCREAMING_SNAKE_CASE__								=   0.8_2
									SCREAMING_SNAKE_CASE__								=   [
									    """fsdp_shard_grad_op_transformer_based_wrap""",
									    """fsdp_full_shard_transformer_based_wrap""",
									]
									SCREAMING_SNAKE_CASE__								=   {
									    """multi_gpu_fp16""": 3200,
									    """fsdp_shard_grad_op_transformer_based_wrap_fp16""": 2000,
									    """fsdp_full_shard_transformer_based_wrap_fp16""": 1900,
									    # 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
									}
									SCREAMING_SNAKE_CASE__								=   160
									SCREAMING_SNAKE_CASE__								=   160

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


							def   _snake_case	(				self     :Union[str, Any]		) -> int:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   os.path.join(self.test_scripts_folder				,					"""test_performance.py"""		)
									SCREAMING_SNAKE_CASE__								=   ["""accelerate""", """launch""", """--num_processes=2""", """--num_machines=1""", """--machine_rank=0""", """--use_fsdp"""]
									for config in self.performance_configs:
											SCREAMING_SNAKE_CASE__								=   cmd.copy()
											for i, strategy in enumerate(__A		):
													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(__A				,					env=os.environ.copy()		)


							def   _snake_case	(				self     :Dict		) -> Union[str, Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   os.path.join(self.test_scripts_folder				,					"""test_checkpointing.py"""		)
									SCREAMING_SNAKE_CASE__								=   [
									    """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(__A		):
											SCREAMING_SNAKE_CASE__								=   cmd.copy()
											cmd_config.append(f'''--fsdp_sharding_strategy={i+1}'''		)
											if strategy != "FULL_SHARD":
													continue
											SCREAMING_SNAKE_CASE__								=   len(__A		)
											for state_dict_type in FSDP_STATE_DICT_TYPE:
													SCREAMING_SNAKE_CASE__								=   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(__A				,					env=os.environ.copy()		)

													SCREAMING_SNAKE_CASE__								=   cmd_config[:-1]
													SCREAMING_SNAKE_CASE__								=   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(__A				,					env=os.environ.copy()		)


							def   _snake_case	(				self     :Tuple		) -> str:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   os.path.join(self.test_scripts_folder				,					"""test_peak_memory_usage.py"""		)
									SCREAMING_SNAKE_CASE__								=   [
									    """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():
											SCREAMING_SNAKE_CASE__								=   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(__A		):
															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(__A				,					env=os.environ.copy()		)







'''simple docstring'''



import sacrebleu as scb
from packaging import version
from sacrebleu import CHRF

import datasets


__UpperCamelCase   :							List[str]         =   """\
@inproceedings{popovic-2015-chrf,
    title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",
    author = \"Popovi{\'c}, Maja\",
    booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",
    month = sep,
    year = \"2015\",
    address = \"Lisbon, Portugal\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://aclanthology.org/W15-3049\",
    doi = \"10.18653/v1/W15-3049\",
    pages = \"392--395\",
}
@inproceedings{popovic-2017-chrf,
    title = \"chr{F}++: words helping character n-grams\",
    author = \"Popovi{\'c}, Maja\",
    booktitle = \"Proceedings of the Second Conference on Machine Translation\",
    month = sep,
    year = \"2017\",
    address = \"Copenhagen, Denmark\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://aclanthology.org/W17-4770\",
    doi = \"10.18653/v1/W17-4770\",
    pages = \"612--618\",
}
@inproceedings{post-2018-call,
    title = \"A Call for Clarity in Reporting {BLEU} Scores\",
    author = \"Post, Matt\",
    booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",
    month = oct,
    year = \"2018\",
    address = \"Belgium, Brussels\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://www.aclweb.org/anthology/W18-6319\",
    pages = \"186--191\",
}
"""

__UpperCamelCase   :							Union[str, Any]         =   """\
ChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,
and ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation
that is already present in sacrebleu.

The implementation here is slightly different from sacrebleu in terms of the required input format. The length of
the references and hypotheses lists need to be the same, so you may need to transpose your references compared to
sacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534

See the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.
"""

__UpperCamelCase   :							str         =   """
Produces ChrF(++) scores for hypotheses given reference translations.

Args:
    predictions (list of str): The predicted sentences.
    references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.
    char_order (int): Character n-gram order. Defaults to `6`.
    word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.
    beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.
    lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.
    whitespace (bool): If `True`, include whitespaces when extracting character n-grams.
    eps_smoothing (bool): If `True`, applies epsilon smoothing similar
    to reference chrF++.py, NLTK and Moses implementations. If `False`,
    it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.

Returns:
    'score' (float): The chrF (chrF++) score,
    'char_order' (int): The character n-gram order,
    'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,
    'beta' (int): Determine the importance of recall w.r.t precision

Examples:
    Example 1--a simple example of calculating chrF:
        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]
        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]
        >>> chrf = datasets.load_metric(\"chrf\")
        >>> results = chrf.compute(predictions=prediction, references=reference)
        >>> print(results)
        {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}

    Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:
        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]
        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]
        >>> chrf = datasets.load_metric(\"chrf\")
        >>> results = chrf.compute(predictions=prediction,
        ...                         references=reference,
        ...                         word_order=2)
        >>> print(results)
        {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}

    Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:
        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]
        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]
        >>> chrf = datasets.load_metric(\"chrf\")
        >>> results = chrf.compute(predictions=prediction,
        ...                         references=reference,
        ...                         word_order=2,
        ...                         lowercase=True)
        >>> print(results)
        {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION   ,   _KWARGS_DESCRIPTION  )
class 				__SCREAMING_SNAKE_CASE							(				datasets.Metric  ):




      def 			__UpperCamelCase				(	self   )				->Union[str, Any]:



         '''simple docstring'''
         if version.parse(scb.__version__   ) < version.parse('1.4.12'   ):
            raise ImportWarning(
                'To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n'
                'You can install it with `pip install "sacrebleu>=1.4.12"`.'   )
         return datasets.MetricInfo(
             description=_DESCRIPTION			, citation=_CITATION			, homepage='https://github.com/mjpost/sacreBLEU#chrf--chrf'			, inputs_description=_KWARGS_DESCRIPTION			, features=datasets.Features(
                 {
                     'predictions': datasets.Value('string'			, id='sequence'   ),
                     'references': datasets.Sequence(datasets.Value('string'			, id='sequence'   )			, id='references'   ),
                 }   )			, codebase_urls=['https://github.com/mjpost/sacreBLEU#chrf--chrf']			, reference_urls=[
                 'https://github.com/m-popovic/chrF',
             ]			, )






      def 			__UpperCamelCase				(	self			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase = CHRF.CHAR_ORDER			, lowerCamelCase = CHRF.WORD_ORDER			, lowerCamelCase = CHRF.BETA			, lowerCamelCase = False			, lowerCamelCase = False			, lowerCamelCase = False			, )				->Union[str, Any]:



         '''simple docstring'''
         __a					  =     len(references[0]   )
         if any(len(lowerCamelCase   ) != references_per_prediction for refs in references   ):
            raise ValueError('Sacrebleu requires the same number of references for each prediction'   )
         __a					  =     [[refs[i] for refs in references] for i in range(lowerCamelCase   )]

         __a					  =     CHRF(lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase   )
         __a					  =     sb_chrf.corpus_score(lowerCamelCase			, lowerCamelCase   )

         return {
             "score": output.score,
             "char_order": output.char_order,
             "word_order": output.word_order,
             "beta": output.beta,
         }