



"""simple docstring"""
import json
import os

from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES
from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType
from ...utils.imports import is_botoa_available
from .config_args import SageMakerConfig
from .config_utils import (
    DYNAMO_BACKENDS,
    _ask_field,
    _ask_options,
    _convert_dynamo_backend,
    _convert_mixed_precision,
    _convert_sagemaker_distributed_mode,
    _convert_yes_no_to_bool,
)


if is_botoa_available():
   import botoa  # noqa: F401





def    __magic_name__ (							lowercase       ):
   SCREAMING_SNAKE_CASE_:       Union[str, Any]   	=botoa.client("""iam"""       )

   SCREAMING_SNAKE_CASE_:       int   	={
       '''Version''': '''2012-10-17''',
       '''Statement''': [
           {'''Effect''': '''Allow''', '''Principal''': {'''Service''': '''sagemaker.amazonaws.com'''}, '''Action''': '''sts:AssumeRole'''}
       ],
   }
   try:
      # create the role, associated with the chosen trust policy
      iam_client.create_role(
          RoleName=__lowerCamelCase							,	AssumeRolePolicyDocument=json.dumps(__lowerCamelCase							,	indent=2       )       )
      SCREAMING_SNAKE_CASE_:       List[Any]   	={
          '''Version''': '''2012-10-17''',
          '''Statement''': [
              {
                  '''Effect''': '''Allow''',
                  '''Action''': [
                      '''sagemaker:*''',
                      '''ecr:GetDownloadUrlForLayer''',
                      '''ecr:BatchGetImage''',
                      '''ecr:BatchCheckLayerAvailability''',
                      '''ecr:GetAuthorizationToken''',
                      '''cloudwatch:PutMetricData''',
                      '''cloudwatch:GetMetricData''',
                      '''cloudwatch:GetMetricStatistics''',
                      '''cloudwatch:ListMetrics''',
                      '''logs:CreateLogGroup''',
                      '''logs:CreateLogStream''',
                      '''logs:DescribeLogStreams''',
                      '''logs:PutLogEvents''',
                      '''logs:GetLogEvents''',
                      '''s3:CreateBucket''',
                      '''s3:ListBucket''',
                      '''s3:GetBucketLocation''',
                      '''s3:GetObject''',
                      '''s3:PutObject''',
                  ],
                  '''Resource''': '''*''',
              }
          ],
      }
      # attach policy to role
      iam_client.put_role_policy(
          RoleName=__lowerCamelCase							,	PolicyName=f'''{role_name}_policy_permission'''							,	PolicyDocument=json.dumps(__lowerCamelCase							,	indent=2       )							,	)
   except iam_client.exceptions.EntityAlreadyExistsException:
      print(f'''role {role_name} already exists. Using existing one'''       )





def    __magic_name__ (							lowercase       ):
   SCREAMING_SNAKE_CASE_:       List[Any]   	=botoa.client("""iam"""       )
   return iam_client.get_role(RoleName=__lowerCamelCase       )["Role"]["Arn"]





def    __magic_name__ (							):
   SCREAMING_SNAKE_CASE_:       Dict   	=_ask_options(
       """How do you want to authorize?"""							,	["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """]							,	__lowerCamelCase							,	)
   SCREAMING_SNAKE_CASE_:       int   	=None
   if credentials_configuration == 0:
      SCREAMING_SNAKE_CASE_:       List[Any]   	=_ask_field("""Enter your AWS Profile name: [default] """							,	default="""default"""       )
      SCREAMING_SNAKE_CASE_:       int   	=aws_profile
   else:
      print(
          """Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,"""
          """`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`"""       )
      SCREAMING_SNAKE_CASE_:       Any   	=_ask_field("""AWS Access Key ID: """       )
      SCREAMING_SNAKE_CASE_:       Any   	=aws_access_key_id

      SCREAMING_SNAKE_CASE_:       List[Any]   	=_ask_field("""AWS Secret Access Key: """       )
      SCREAMING_SNAKE_CASE_:       List[Any]   	=aws_secret_access_key

   SCREAMING_SNAKE_CASE_:       Tuple   	=_ask_field("""Enter your AWS Region: [us-east-1]"""							,	default="""us-east-1"""       )
   SCREAMING_SNAKE_CASE_:       str   	=aws_region

   SCREAMING_SNAKE_CASE_:       Optional[int]   	=_ask_options(
       """Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?"""							,	["""Provide IAM Role name""", """Create new IAM role using credentials"""]							,	__lowerCamelCase							,	)
   if role_management == 0:
      SCREAMING_SNAKE_CASE_:       str   	=_ask_field("""Enter your IAM role name: """       )
   else:
      SCREAMING_SNAKE_CASE_:       Tuple   	='''accelerate_sagemaker_execution_role'''
      print(f'''Accelerate will create an iam role "{iam_role_name}" using the provided credentials'''       )
      _create_iam_role_for_sagemaker(__lowerCamelCase       )

   SCREAMING_SNAKE_CASE_:       Tuple   	=_ask_field(
       """Do you want to use custom Docker image? [yes/NO]: """							,	_convert_yes_no_to_bool							,	default=__lowerCamelCase							,	error_message="""Please enter yes or no."""							,	)
   SCREAMING_SNAKE_CASE_:       Tuple   	=None
   if is_custom_docker_image:
      SCREAMING_SNAKE_CASE_:       List[Any]   	=_ask_field("""Enter your Docker image: """							,	lambda lowercase       : str(__lowerCamelCase       ).lower()       )

   SCREAMING_SNAKE_CASE_:       Union[str, Any]   	=_ask_field(
       """Do you want to provide SageMaker input channels with data locations? [yes/NO]: """							,	_convert_yes_no_to_bool							,	default=__lowerCamelCase							,	error_message="""Please enter yes or no."""							,	)
   SCREAMING_SNAKE_CASE_:       Tuple   	=None
   if is_sagemaker_inputs_enabled:
      SCREAMING_SNAKE_CASE_:       Union[str, Any]   	=_ask_field(
          """Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """							,	lambda lowercase       : str(__lowerCamelCase       ).lower()							,	)

   SCREAMING_SNAKE_CASE_:       int   	=_ask_field(
       """Do you want to enable SageMaker metrics? [yes/NO]: """							,	_convert_yes_no_to_bool							,	default=__lowerCamelCase							,	error_message="""Please enter yes or no."""							,	)
   SCREAMING_SNAKE_CASE_:       Dict   	=None
   if is_sagemaker_metrics_enabled:
      SCREAMING_SNAKE_CASE_:       Any   	=_ask_field(
          """Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """							,	lambda lowercase       : str(__lowerCamelCase       ).lower()							,	)

   SCREAMING_SNAKE_CASE_:       Optional[int]   	=_ask_options(
       """What is the distributed mode?"""							,	["""No distributed training""", """Data parallelism"""]							,	_convert_sagemaker_distributed_mode							,	)
   SCREAMING_SNAKE_CASE_:       Any   	={}
   SCREAMING_SNAKE_CASE_:       List[str]   	=_ask_field(
       """Do you wish to optimize your script with torch dynamo?[yes/NO]:"""							,	_convert_yes_no_to_bool							,	default=__lowerCamelCase							,	error_message="""Please enter yes or no."""							,	)
   if use_dynamo:
      SCREAMING_SNAKE_CASE_:       Dict   	='''dynamo_'''
      SCREAMING_SNAKE_CASE_:       Dict   	=_ask_options(
          """Which dynamo backend would you like to use?"""							,	[x.lower() for x in DYNAMO_BACKENDS]							,	_convert_dynamo_backend							,	default=2							,	)
      SCREAMING_SNAKE_CASE_:       Optional[int]   	=_ask_field(
          """Do you want to customize the defaults sent to torch.compile? [yes/NO]: """							,	_convert_yes_no_to_bool							,	default=__lowerCamelCase							,	error_message="""Please enter yes or no."""							,	)

      if use_custom_options:
         SCREAMING_SNAKE_CASE_:       Union[str, Any]   	=_ask_options(
             """Which mode do you want to use?"""							,	__lowerCamelCase							,	lambda lowercase       : TORCH_DYNAMO_MODES[int(__lowerCamelCase       )]							,	default="""default"""							,	)
         SCREAMING_SNAKE_CASE_:       Dict   	=_ask_field(
             """Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """							,	_convert_yes_no_to_bool							,	default=__lowerCamelCase							,	error_message="""Please enter yes or no."""							,	)
         SCREAMING_SNAKE_CASE_:       List[Any]   	=_ask_field(
             """Do you want to enable dynamic shape tracing? [yes/NO]: """							,	_convert_yes_no_to_bool							,	default=__lowerCamelCase							,	error_message="""Please enter yes or no."""							,	)
   SCREAMING_SNAKE_CASE_:       Dict   	='''Which EC2 instance type you want to use for your training?'''
   if distributed_type != SageMakerDistributedType.NO:
      SCREAMING_SNAKE_CASE_:       Optional[int]   	=_ask_options(
          __lowerCamelCase							,	__lowerCamelCase							,	lambda lowercase       : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(__lowerCamelCase       )]       )
   else:
      eca_instance_query += "? [ml.p3.2xlarge]:"
      SCREAMING_SNAKE_CASE_:       Tuple   	=_ask_field(__lowerCamelCase							,	lambda lowercase       : str(__lowerCamelCase       ).lower()							,	default="""ml.p3.2xlarge"""       )

   SCREAMING_SNAKE_CASE_:       List[Any]   	=1
   if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL):
      SCREAMING_SNAKE_CASE_:       Dict   	=_ask_field(
          """How many machines do you want use? [1]: """							,	__lowerCamelCase							,	default=1							,	)

   SCREAMING_SNAKE_CASE_:       Any   	=_ask_options(
       """Do you wish to use FP16 or BF16 (mixed precision)?"""							,	["""no""", """fp16""", """bf16""", """fp8"""]							,	_convert_mixed_precision							,	)

   if use_dynamo and mixed_precision == "no":
      print(
          """Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts."""       )

   return SageMakerConfig(
       image_uri=__lowerCamelCase							,	compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER							,	distributed_type=__lowerCamelCase							,	use_cpu=__lowerCamelCase							,	dynamo_config=__lowerCamelCase							,	eca_instance_type=__lowerCamelCase							,	profile=__lowerCamelCase							,	region=__lowerCamelCase							,	iam_role_name=__lowerCamelCase							,	mixed_precision=__lowerCamelCase							,	num_machines=__lowerCamelCase							,	sagemaker_inputs_file=__lowerCamelCase							,	sagemaker_metrics_file=__lowerCamelCase							,	)








"""simple docstring"""






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      snake_case__   (		__lowerCamelCase				:    Union[str, Any]							,		__lowerCamelCase				:    Tuple							,		__lowerCamelCase				:    Any							,		__lowerCamelCase				:    Tuple							,		__lowerCamelCase				:    Tuple=True							,		__lowerCamelCase				:    Dict="pt"	):
			"""simple docstring"""
			lowerCamelCase__		:		str			={'''add_prefix_space''': True} if isinstance(__lowerCamelCase							,		__lowerCamelCase	) and not line.startswith(''' '''	) else {}
			lowerCamelCase__		:		int			=padding_side
			return tokenizer(
			    [line]							,		max_length=__lowerCamelCase							,		padding='''max_length''' if pad_to_max_length else None							,		truncation=__lowerCamelCase							,		return_tensors=__lowerCamelCase							,		add_special_tokens=__lowerCamelCase							,		**__lowerCamelCase							,		)






def      snake_case__   (		__lowerCamelCase				:    str							,		__lowerCamelCase				:    List[Any]							,		__lowerCamelCase				:    Optional[int]=None							,		):
			"""simple docstring"""
			lowerCamelCase__		:		Any			=input_ids.ne(__lowerCamelCase	).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        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_   ):


					'''simple docstring'''





					def __init__(       self							:  str,  lowerCamelCase							:  Union[str, Any],  lowerCamelCase							:  Dict,  lowerCamelCase							:  Union[str, Any],  lowerCamelCase							:  Dict,  lowerCamelCase							:  str="train",  lowerCamelCase							:  List[Any]=None,  lowerCamelCase							:  Tuple=None,  lowerCamelCase							:  List[str]=None,  lowerCamelCase							:  int="",  )->					List[Any]:
								super().__init__()
								lowerCamelCase__		:		Tuple			=Path(lowerCamelCase     ).joinpath(type_path + '''.source'''     )
								lowerCamelCase__		:		str			=Path(lowerCamelCase     ).joinpath(type_path + '''.target'''     )
								lowerCamelCase__		:		Dict			=self.get_char_lens(self.src_file     )
								lowerCamelCase__		:		Tuple			=max_source_length
								lowerCamelCase__		:		Optional[int]			=max_target_length
								assert min(self.src_lens     ) > 0, F'''found empty line in {self.src_file}'''
								lowerCamelCase__		:		Dict			=tokenizer
								lowerCamelCase__		:		List[str]			=prefix
								if n_obs is not None:
											lowerCamelCase__		:		int			=self.src_lens[:n_obs]
								lowerCamelCase__		:		Dict			=src_lang
								lowerCamelCase__		:		Tuple			=tgt_lang



					def __len__(       self							:  Dict     )->					Optional[int]:
								return len(self.src_lens     )



					def __getitem__(       self							:  List[str],  lowerCamelCase							:  Optional[int]     )->					Dict[str, torch.Tensor]:
								lowerCamelCase__		:		List[Any]			=index + 1  # linecache starts at 1
								lowerCamelCase__		:		Optional[int]			=self.prefix + linecache.getline(str(self.src_file     ),  lowerCamelCase     ).rstrip('''\n'''     )
								lowerCamelCase__		:		Optional[Any]			=linecache.getline(str(self.tgt_file     ),  lowerCamelCase     ).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,  lowerCamelCase     ):
											source_line += self.tokenizer.eos_token
											tgt_line += self.tokenizer.eos_token

								# Pad source and target to the right
								lowerCamelCase__		:		Optional[int]			=(
								    self.tokenizer.question_encoder if isinstance(self.tokenizer,  lowerCamelCase     ) else self.tokenizer
								)
								lowerCamelCase__		:		Tuple			=self.tokenizer.generator if isinstance(self.tokenizer,  lowerCamelCase     ) else self.tokenizer

								lowerCamelCase__		:		Optional[int]			=encode_line(lowerCamelCase,  lowerCamelCase,  self.max_source_length,  '''right'''     )
								lowerCamelCase__		:		str			=encode_line(lowerCamelCase,  lowerCamelCase,  self.max_target_length,  '''right'''     )

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



					@staticmethod
					def 		snake_case       (       lowerCamelCase							:  Union[str, Any]     )->					Optional[int]:
								return [len(lowerCamelCase     ) for x in Path(lowerCamelCase     ).open().readlines()]




					def 		snake_case       (       self							:  str,  lowerCamelCase							:  str     )->					Dict[str, torch.Tensor]:
								lowerCamelCase__		:		List[Any]			=torch.stack([x['''input_ids'''] for x in batch]     )
								lowerCamelCase__		:		int			=torch.stack([x['''attention_mask'''] for x in batch]     )
								lowerCamelCase__		:		Union[str, Any]			=torch.stack([x['''decoder_input_ids'''] for x in batch]     )
								lowerCamelCase__		:		str			=(
								    self.tokenizer.generator.pad_token_id
								    if isinstance(self.tokenizer,  lowerCamelCase     )
								    else self.tokenizer.pad_token_id
								)
								lowerCamelCase__		:		List[str]			=(
								    self.tokenizer.question_encoder.pad_token_id
								    if isinstance(self.tokenizer,  lowerCamelCase     )
								    else self.tokenizer.pad_token_id
								)
								lowerCamelCase__		:		Optional[int]			=trim_batch(lowerCamelCase,  lowerCamelCase     )
								lowerCamelCase__	,   lowerCamelCase__		:		Any			=trim_batch(lowerCamelCase,  lowerCamelCase,  attention_mask=lowerCamelCase     )
								lowerCamelCase__		:		List[str]			={
								    '''input_ids''': source_ids,
								    '''attention_mask''': source_mask,
								    '''decoder_input_ids''': y,
								}
								return batch





_lowercase : Any      						=						getLogger(__name__)






def      snake_case__   (		__lowerCamelCase				:    List[List]	):
			"""simple docstring"""
			return list(itertools.chain.from_iterable(__lowerCamelCase	)	)






def      snake_case__   (		__lowerCamelCase				:    str	):
			"""simple docstring"""
			lowerCamelCase__		:		Dict			=get_git_info()
			save_json(__lowerCamelCase							,		os.path.join(__lowerCamelCase							,		'''git_log.json'''	)	)






def      snake_case__   (		__lowerCamelCase				:    Union[str, Any]							,		__lowerCamelCase				:    Optional[int]							,		__lowerCamelCase				:    Dict=4							,		**__lowerCamelCase				:    int	):
			"""simple docstring"""
			with open(__lowerCamelCase							,		'''w'''	) as f:
						json.dump(__lowerCamelCase							,		__lowerCamelCase							,		indent=__lowerCamelCase							,		**__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    List[Any]	):
			"""simple docstring"""
			with open(__lowerCamelCase	) as f:
						return json.load(__lowerCamelCase	)






def      snake_case__   (		):
			"""simple docstring"""
			lowerCamelCase__		:		List[Any]			=git.Repo(search_parent_directories=__lowerCamelCase	)
			lowerCamelCase__		:		Union[str, Any]			={
			    '''repo_id''': str(__lowerCamelCase	),
			    '''repo_sha''': str(repo.head.object.hexsha	),
			    '''repo_branch''': str(repo.active_branch	),
			    '''hostname''': str(socket.gethostname()	),
			}
			return repo_infos






def      snake_case__   (		__lowerCamelCase				:    Callable							,		__lowerCamelCase				:    Iterable	):
			"""simple docstring"""
			return list(map(__lowerCamelCase							,		__lowerCamelCase	)	)






def      snake_case__   (		__lowerCamelCase				:    Any							,		__lowerCamelCase				:    List[Any]	):
			"""simple docstring"""
			with open(__lowerCamelCase							,		'''wb'''	) as f:
						return pickle.dump(__lowerCamelCase							,		__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    str	):
			"""simple docstring"""

			def remove_articles(__lowerCamelCase				:    List[Any]	):
						return re.sub(R'''\b(a|an|the)\b'''							,		''' '''							,		__lowerCamelCase	)

			def white_space_fix(__lowerCamelCase				:    Any	):
						return " ".join(text.split()	)

			def remove_punc(__lowerCamelCase				:    Optional[Any]	):
						lowerCamelCase__		:		Tuple			=set(string.punctuation	)
						return "".join(ch for ch in text if ch not in exclude	)

			def lower(__lowerCamelCase				:    Any	):
						return text.lower()

			return white_space_fix(remove_articles(remove_punc(lower(__lowerCamelCase	)	)	)	)






def      snake_case__   (		__lowerCamelCase				:    List[str]							,		__lowerCamelCase				:    List[str]	):
			"""simple docstring"""
			lowerCamelCase__		:		List[str]			=normalize_answer(__lowerCamelCase	).split()
			lowerCamelCase__		:		List[str]			=normalize_answer(__lowerCamelCase	).split()
			lowerCamelCase__		:		Optional[int]			=Counter(__lowerCamelCase	) & Counter(__lowerCamelCase	)
			lowerCamelCase__		:		Union[str, Any]			=sum(common.values()	)
			if num_same == 0:
						return 0
			lowerCamelCase__		:		Dict			=1.0 * num_same / len(__lowerCamelCase	)
			lowerCamelCase__		:		List[str]			=1.0 * num_same / len(__lowerCamelCase	)
			lowerCamelCase__		:		Union[str, Any]			=(2 * precision * recall) / (precision + recall)
			return fa






def      snake_case__   (		__lowerCamelCase				:    Dict							,		__lowerCamelCase				:    int	):
			"""simple docstring"""
			return normalize_answer(__lowerCamelCase	) == normalize_answer(__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    List[str]							,		__lowerCamelCase				:    List[str]	):
			"""simple docstring"""
			assert len(__lowerCamelCase	) == len(__lowerCamelCase	)
			lowerCamelCase__		:		Any			=0
			for hypo, pred in zip(__lowerCamelCase							,		__lowerCamelCase	):
						em += exact_match_score(__lowerCamelCase							,		__lowerCamelCase	)
			if len(__lowerCamelCase	) > 0:
						em /= len(__lowerCamelCase	)
			return {"em": em}






def      snake_case__   (		__lowerCamelCase				:    List[str]	):
			"""simple docstring"""
			return model_prefix.startswith('''rag'''	)






def      snake_case__   (		__lowerCamelCase				:    Any							,		__lowerCamelCase				:    List[str]							,		__lowerCamelCase				:    str	):
			"""simple docstring"""
			lowerCamelCase__		:		Any			={p: p for p in extra_params}
			# T5 models don't have `dropout` param, they have `dropout_rate` instead
			lowerCamelCase__		:		Optional[int]			='''dropout_rate'''
			for p in extra_params:
						if getattr(__lowerCamelCase							,		__lowerCamelCase							,		__lowerCamelCase	):
									if not hasattr(__lowerCamelCase							,		__lowerCamelCase	) and not hasattr(__lowerCamelCase							,		equivalent_param[p]	):
												logger.info('''config doesn\'t have a `{}` attribute'''.format(__lowerCamelCase	)	)
												delattr(__lowerCamelCase							,		__lowerCamelCase	)
												continue
									lowerCamelCase__		:		List[Any]			=p if hasattr(__lowerCamelCase							,		__lowerCamelCase	) else equivalent_param[p]
									setattr(__lowerCamelCase							,		__lowerCamelCase							,		getattr(__lowerCamelCase							,		__lowerCamelCase	)	)
									delattr(__lowerCamelCase							,		__lowerCamelCase	)
			return hparams, config




