


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(4_2)

SCREAMING_SNAKE_CASE							    =							'bert-base-cased'
SCREAMING_SNAKE_CASE							    =							'fp16'
SCREAMING_SNAKE_CASE							    =							'bf16'
SCREAMING_SNAKE_CASE							    =							[FPaa, BFaa]


@require_fsdp
@require_cuda
class     __UpperCAmelCase							(       __A							):


     """simple docstring"""


     def 	snake_case_  (	self    ):
        super().setUp()

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


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

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


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

        for i, prefetch_policy in enumerate(__A    ):
           __a					=  self.dist_env.copy()
           __a					=  prefetch_policy
           with mockenv_context(**__A    ):
              __a					=  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    ):
        from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType

        for i, state_dict_type in enumerate(__A    ):
           __a					=  self.dist_env.copy()
           __a					=  state_dict_type
           with mockenv_context(**__A    ):
              __a					=  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    ):
        __a					=  AutoModel.from_pretrained(__A    )
        for policy in FSDP_AUTO_WRAP_POLICY:
           __a					=  self.dist_env.copy()
           __a					=  policy
           if policy == "TRANSFORMER_BASED_WRAP":
              __a					=  """BertLayer"""
           elif policy == "SIZE_BASED_WRAP":
              __a					=  """2000"""
           with mockenv_context(**__A    ):
              __a					=  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    )

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

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


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

        for mp_dtype in dtypes:
           __a					=  self.dist_env.copy()
           __a					=  mp_dtype
           with mockenv_context(**__A    ):
              __a					=  Accelerator()
              if mp_dtype == "fp16":
                 __a					=  torch.floataa
              elif mp_dtype == "bf16":
                 __a					=  torch.bfloataa
              __a					=  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    ):
        from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload

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







@require_fsdp
@require_multi_gpu
@slow
class     __UpperCAmelCase							(       __A							):


     """simple docstring"""


     def 	snake_case_  (	self    ):
        super().setUp()
        __a					=  0.82
        __a					=  [
            """fsdp_shard_grad_op_transformer_based_wrap""",
            """fsdp_full_shard_transformer_based_wrap""",
        ]
        __a					=  {
            """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
        }
        __a					=  160
        __a					=  160

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


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

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







import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List

import git
import torch
from torch.utils.data import Dataset

from transformers import BartTokenizer, RagTokenizer, TaTokenizer


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase=True							,      _UpperCamelCase="pt"	):


			'''simple docstring'''







			__lowercase			       = {'''add_prefix_space''': True} if isinstance(_UpperCamelCase							,      _UpperCamelCase	) and not line.startswith(''' '''	) else {}
			__lowercase			       = padding_side
			return tokenizer(
			    [line]							,      max_length=_UpperCamelCase							,      padding='''max_length''' if pad_to_max_length else None							,      truncation=_UpperCamelCase							,      return_tensors=_UpperCamelCase							,      add_special_tokens=_UpperCamelCase							,      **_UpperCamelCase							,      )


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase=None							,      ):


			'''simple docstring'''







			__lowercase			       = input_ids.ne(_UpperCamelCase	).any(dim=0	)
			if attention_mask is None:
						return input_ids[:, keep_column_mask]
			else:
						return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])
class 						lowerCamelCase_							(					lowerCAmelCase__					):



					'''simple docstring'''







					def __init__(					self			,							snake_case_			,							snake_case_			,							snake_case_			,							snake_case_			,							snake_case_="train"			,							snake_case_=None			,							snake_case_=None			,							snake_case_=None			,							snake_case_=""			,							) ->      Tuple:







								'''simple docstring'''

								super().__init__()
								__lowercase			       = Path(snake_case_    ).joinpath(type_path + '''.source'''    )
								__lowercase			       = Path(snake_case_    ).joinpath(type_path + '''.target'''    )
								__lowercase			       = self.get_char_lens(self.src_file    )
								__lowercase			       = max_source_length
								__lowercase			       = max_target_length
								assert min(self.src_lens    ) > 0, F'found empty line in {self.src_file}'
								__lowercase			       = tokenizer
								__lowercase			       = prefix
								if n_obs is not None:
											__lowercase			       = self.src_lens[:n_obs]
								__lowercase			       = src_lang
								__lowercase			       = tgt_lang






					def __len__(					self    ) ->      List[Any]:







								'''simple docstring'''

								return len(self.src_lens    )






					def __getitem__(					self			,							snake_case_    ) ->      Dict[str, torch.Tensor]:







								'''simple docstring'''

								__lowercase			       = index + 1  # linecache starts at 1
								__lowercase			       = self.prefix + linecache.getline(str(self.src_file    )			,							snake_case_    ).rstrip('''\n'''    )
								__lowercase			       = linecache.getline(str(self.tgt_file    )			,							snake_case_    ).rstrip('''\n'''    )
								assert source_line, F'empty source line for index {index}'
								assert tgt_line, F'empty tgt line for index {index}'

								# Need to add eos token manually for T5
								if isinstance(self.tokenizer			,							snake_case_    ):
											source_line += self.tokenizer.eos_token
											tgt_line += self.tokenizer.eos_token

								# Pad source and target to the right
								__lowercase			       = (
								    self.tokenizer.question_encoder if isinstance(self.tokenizer			,							snake_case_    ) else self.tokenizer
								)
								__lowercase			       = self.tokenizer.generator if isinstance(self.tokenizer			,							snake_case_    ) else self.tokenizer

								__lowercase			       = encode_line(snake_case_			,							snake_case_			,							self.max_source_length			,							'''right'''    )
								__lowercase			       = encode_line(snake_case_			,							snake_case_			,							self.max_target_length			,							'''right'''    )

								__lowercase			       = source_inputs['''input_ids'''].squeeze()
								__lowercase			       = target_inputs['''input_ids'''].squeeze()
								__lowercase			       = source_inputs['''attention_mask'''].squeeze()
								return {
								    "input_ids": source_ids,
								    "attention_mask": src_mask,
								    "decoder_input_ids": target_ids,
								}






					@staticmethod
					def A   (					snake_case_    ) ->      Any:







								'''simple docstring'''

								return [len(snake_case_    ) for x in Path(snake_case_    ).open().readlines()]






					def A   (					self			,							snake_case_    ) ->      Dict[str, torch.Tensor]:







								'''simple docstring'''

								__lowercase			       = torch.stack([x['''input_ids'''] for x in batch]    )
								__lowercase			       = torch.stack([x['''attention_mask'''] for x in batch]    )
								__lowercase			       = torch.stack([x['''decoder_input_ids'''] for x in batch]    )
								__lowercase			       = (
								    self.tokenizer.generator.pad_token_id
								    if isinstance(self.tokenizer			,							snake_case_    )
								    else self.tokenizer.pad_token_id
								)
								__lowercase			       = (
								    self.tokenizer.question_encoder.pad_token_id
								    if isinstance(self.tokenizer			,							snake_case_    )
								    else self.tokenizer.pad_token_id
								)
								__lowercase			       = trim_batch(snake_case_			,							snake_case_    )
								__lowercase       ,			__lowercase			       = trim_batch(snake_case_			,							snake_case_			,							attention_mask=snake_case_    )
								__lowercase			       = {
								    '''input_ids''': source_ids,
								    '''attention_mask''': source_mask,
								    '''decoder_input_ids''': y,
								}
								return batch




a			:			int												=					getLogger(__name__)


def 		lowercase_	(  _UpperCamelCase	):


			'''simple docstring'''







			return list(itertools.chain.from_iterable(_UpperCamelCase	)	)


def 		lowercase_	(  _UpperCamelCase	):


			'''simple docstring'''







			__lowercase			       = get_git_info()
			save_json(_UpperCamelCase							,      os.path.join(_UpperCamelCase							,      '''git_log.json'''	)	)


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase=4							,      **_UpperCamelCase	):


			'''simple docstring'''







			with open(_UpperCamelCase							,      '''w'''	) as f:
						json.dump(_UpperCamelCase							,      _UpperCamelCase							,      indent=_UpperCamelCase							,      **_UpperCamelCase	)


def 		lowercase_	(  _UpperCamelCase	):


			'''simple docstring'''







			with open(_UpperCamelCase	) as f:
						return json.load(_UpperCamelCase	)


def 		lowercase_	(  ):


			'''simple docstring'''







			__lowercase			       = git.Repo(search_parent_directories=_UpperCamelCase	)
			__lowercase			       = {
			    '''repo_id''': str(_UpperCamelCase	),
			    '''repo_sha''': str(repo.head.object.hexsha	),
			    '''repo_branch''': str(repo.active_branch	),
			    '''hostname''': str(socket.gethostname()	),
			}
			return repo_infos


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase	):


			'''simple docstring'''







			return list(map(_UpperCamelCase							,      _UpperCamelCase	)	)


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase	):


			'''simple docstring'''







			with open(_UpperCamelCase							,      '''wb'''	) as f:
						return pickle.dump(_UpperCamelCase							,      _UpperCamelCase	)


def 		lowercase_	(  _UpperCamelCase	):


			'''simple docstring'''







			def remove_articles(_UpperCamelCase	):
						return re.sub(r'''\b(a|an|the)\b'''							,      ''' '''							,      _UpperCamelCase	)

			def white_space_fix(_UpperCamelCase	):
						return " ".join(text.split()	)

			def remove_punc(_UpperCamelCase	):
						__lowercase			       = set(string.punctuation	)
						return "".join(ch for ch in text if ch not in exclude	)

			def lower(_UpperCamelCase	):
						return text.lower()

			return white_space_fix(remove_articles(remove_punc(lower(_UpperCamelCase	)	)	)	)


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase	):


			'''simple docstring'''







			__lowercase			       = normalize_answer(_UpperCamelCase	).split()
			__lowercase			       = normalize_answer(_UpperCamelCase	).split()
			__lowercase			       = Counter(_UpperCamelCase	) & Counter(_UpperCamelCase	)
			__lowercase			       = sum(common.values()	)
			if num_same == 0:
						return 0
			__lowercase			       = 1.0 * num_same / len(_UpperCamelCase	)
			__lowercase			       = 1.0 * num_same / len(_UpperCamelCase	)
			__lowercase			       = (2 * precision * recall) / (precision + recall)
			return fa


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase	):


			'''simple docstring'''







			return normalize_answer(_UpperCamelCase	) == normalize_answer(_UpperCamelCase	)


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase	):


			'''simple docstring'''







			assert len(_UpperCamelCase	) == len(_UpperCamelCase	)
			__lowercase			       = 0
			for hypo, pred in zip(_UpperCamelCase							,      _UpperCamelCase	):
						em += exact_match_score(_UpperCamelCase							,      _UpperCamelCase	)
			if len(_UpperCamelCase	) > 0:
						em /= len(_UpperCamelCase	)
			return {"em": em}


def 		lowercase_	(  _UpperCamelCase	):


			'''simple docstring'''







			return model_prefix.startswith('''rag'''	)





def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase	):


			'''simple docstring'''







			__lowercase			       = {p: p for p in extra_params}
			# T5 models don't have `dropout` param, they have `dropout_rate` instead
			__lowercase			       = '''dropout_rate'''
			for p in extra_params:
						if getattr(_UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase	):
									if not hasattr(_UpperCamelCase							,      _UpperCamelCase	) and not hasattr(_UpperCamelCase							,      equivalent_param[p]	):
												logger.info('''config doesn\'t have a `{}` attribute'''.format(_UpperCamelCase	)	)
												delattr(_UpperCamelCase							,      _UpperCamelCase	)
												continue
									__lowercase			       = p if hasattr(_UpperCamelCase							,      _UpperCamelCase	) else equivalent_param[p]
									setattr(_UpperCamelCase							,      _UpperCamelCase							,      getattr(_UpperCamelCase							,      _UpperCamelCase	)	)
									delattr(_UpperCamelCase							,      _UpperCamelCase	)
			return hparams, config


