



"""simple docstring"""






# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
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      snake_case__   (		__lowerCamelCase				:    str	):
			"""simple docstring"""
			lowerCamelCase__		:		Union[str, Any]			=botoa.client('''iam'''	)

			lowerCamelCase__		:		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	)	)
						lowerCamelCase__		:		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      snake_case__   (		__lowerCamelCase				:    Any	):
			"""simple docstring"""
			lowerCamelCase__		:		List[Any]			=botoa.client('''iam'''	)
			return iam_client.get_role(RoleName=__lowerCamelCase	)["Role"]["Arn"]






def      snake_case__   (		):
			"""simple docstring"""
			lowerCamelCase__		:		Dict			=_ask_options(
			    '''How do you want to authorize?'''							,		['''AWS Profile''', '''Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) ''']							,		__lowerCamelCase							,		)
			lowerCamelCase__		:		int			=None
			if credentials_configuration == 0:
						lowerCamelCase__		:		List[Any]			=_ask_field('''Enter your AWS Profile name: [default] '''							,		default='''default'''	)
						lowerCamelCase__		:		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`'''	)
						lowerCamelCase__		:		Any			=_ask_field('''AWS Access Key ID: '''	)
						lowerCamelCase__		:		Any			=aws_access_key_id

						lowerCamelCase__		:		List[Any]			=_ask_field('''AWS Secret Access Key: '''	)
						lowerCamelCase__		:		List[Any]			=aws_secret_access_key

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

			lowerCamelCase__		:		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:
						lowerCamelCase__		:		str			=_ask_field('''Enter your IAM role name: '''	)
			else:
						lowerCamelCase__		:		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	)

			lowerCamelCase__		:		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.'''							,		)
			lowerCamelCase__		:		Tuple			=None
			if is_custom_docker_image:
						lowerCamelCase__		:		List[Any]			=_ask_field('''Enter your Docker image: '''							,		lambda __lowerCamelCase	: str(__lowerCamelCase	).lower()	)

			lowerCamelCase__		:		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.'''							,		)
			lowerCamelCase__		:		Tuple			=None
			if is_sagemaker_inputs_enabled:
						lowerCamelCase__		:		Union[str, Any]			=_ask_field(
						    '''Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): '''							,		lambda __lowerCamelCase	: str(__lowerCamelCase	).lower()							,		)

			lowerCamelCase__		:		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.'''							,		)
			lowerCamelCase__		:		Dict			=None
			if is_sagemaker_metrics_enabled:
						lowerCamelCase__		:		Any			=_ask_field(
						    '''Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): '''							,		lambda __lowerCamelCase	: str(__lowerCamelCase	).lower()							,		)

			lowerCamelCase__		:		Optional[int]			=_ask_options(
			    '''What is the distributed mode?'''							,		['''No distributed training''', '''Data parallelism''']							,		_convert_sagemaker_distributed_mode							,		)
			lowerCamelCase__		:		Any			={}
			lowerCamelCase__		:		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:
						lowerCamelCase__		:		Dict			='''dynamo_'''
						lowerCamelCase__		:		Dict			=_ask_options(
						    '''Which dynamo backend would you like to use?'''							,		[x.lower() for x in DYNAMO_BACKENDS]							,		_convert_dynamo_backend							,		default=2							,		)
						lowerCamelCase__		:		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:
									lowerCamelCase__		:		Union[str, Any]			=_ask_options(
									    '''Which mode do you want to use?'''							,		__lowerCamelCase							,		lambda __lowerCamelCase	: TORCH_DYNAMO_MODES[int(__lowerCamelCase	)]							,		default='''default'''							,		)
									lowerCamelCase__		:		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.'''							,		)
									lowerCamelCase__		:		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.'''							,		)
			lowerCamelCase__		:		Dict			='''Which EC2 instance type you want to use for your training?'''
			if distributed_type != SageMakerDistributedType.NO:
						lowerCamelCase__		:		Optional[int]			=_ask_options(
						    __lowerCamelCase							,		__lowerCamelCase							,		lambda __lowerCamelCase	: SAGEMAKER_PARALLEL_EC2_INSTANCES[int(__lowerCamelCase	)]	)
			else:
						eca_instance_query += "? [ml.p3.2xlarge]:"
						lowerCamelCase__		:		Tuple			=_ask_field(__lowerCamelCase							,		lambda __lowerCamelCase	: str(__lowerCamelCase	).lower()							,		default='''ml.p3.2xlarge'''	)

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

			lowerCamelCase__		:		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 os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


_lowercase : Optional[int]      						=						logging.get_logger(__name__)

_lowercase : Tuple      						=						list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
_lowercase : Tuple      						=						tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)

@dataclass
class        __SCREAMING_SNAKE_CASE	:


					'''simple docstring'''





					_a   			=							field(
					    default=lowerCAmelCase_		,   metadata={'help': 'Model type selected in the list: ' + ', '.join(lowerCAmelCase_   )}   )
					_a   			=							field(
					    default=lowerCAmelCase_		,   metadata={'help': 'The input data dir. Should contain the .json files for the SQuAD task.'}   )
					_a   			=							field(
					    default=1_2_8		,   metadata={
					        'help': (
					            'The maximum total input sequence length after tokenization. Sequences longer '
					            'than this will be truncated, sequences shorter will be padded.'
					        )
					    }		,   )
					_a   			=							field(
					    default=1_2_8		,   metadata={'help': 'When splitting up a long document into chunks, how much stride to take between chunks.'}		,   )
					_a   			=							field(
					    default=6_4		,   metadata={
					        'help': (
					            'The maximum number of tokens for the question. Questions longer than this will '
					            'be truncated to this length.'
					        )
					    }		,   )
					_a   			=							field(
					    default=3_0		,   metadata={
					        'help': (
					            'The maximum length of an answer that can be generated. This is needed because the start '
					            'and end predictions are not conditioned on one another.'
					        )
					    }		,   )
					_a   			=							field(
					    default=lowerCAmelCase_		,   metadata={'help': 'Overwrite the cached training and evaluation sets'}   )
					_a   			=							field(
					    default=lowerCAmelCase_		,   metadata={'help': 'If true, the SQuAD examples contain some that do not have an answer.'}   )
					_a   			=							field(
					    default=0.0		,   metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'}   )
					_a   			=							field(
					    default=2_0		,   metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'}   )
					_a   			=							field(
					    default=0		,   metadata={
					        'help': (
					            'language id of input for language-specific xlm models (see'
					            ' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'
					        )
					    }		,   )
					_a   			=							field(default=1		,   metadata={'help': 'multiple threads for converting example to features'}   )





class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_   ):


					'''simple docstring'''





					_a   			=							'train'
					_a   			=							'dev'





class        __SCREAMING_SNAKE_CASE	(      lowerCAmelCase_   ):


					'''simple docstring'''





					_a   			=							42
					_a   			=							42
					_a   			=							42
					_a   			=							42



					def __init__(       self							:  Dict,  lowerCamelCase							:  SquadDataTrainingArguments,  lowerCamelCase							:  PreTrainedTokenizer,  lowerCamelCase							:  Optional[int] = None,  lowerCamelCase							:  Union[str, Split] = Split.train,  lowerCamelCase							:  Optional[bool] = False,  lowerCamelCase							:  Optional[str] = None,  lowerCamelCase							:  Optional[str] = "pt",  )->					List[str]:
								lowerCamelCase__		:		List[str]			=args
								lowerCamelCase__		:		Optional[Any]			=is_language_sensitive
								lowerCamelCase__		:		Any			=SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
								if isinstance(lowerCamelCase,  lowerCamelCase     ):
											try:
														lowerCamelCase__		:		int			=Split[mode]
											except KeyError:
														raise KeyError('''mode is not a valid split name'''     )
								lowerCamelCase__		:		Optional[Any]			=mode
								# Load data features from cache or dataset file
								lowerCamelCase__		:		Any			='''v2''' if args.version_2_with_negative else '''v1'''
								lowerCamelCase__		:		Optional[int]			=os.path.join(
								    cache_dir if cache_dir is not None else args.data_dir,  F'''cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}''',  )

								# Make sure only the first process in distributed training processes the dataset,
								# and the others will use the cache.
								lowerCamelCase__		:		Optional[Any]			=cached_features_file + '''.lock'''
								with FileLock(lowerCamelCase     ):
											if os.path.exists(lowerCamelCase     ) and not args.overwrite_cache:
														lowerCamelCase__		:		Tuple			=time.time()
														lowerCamelCase__		:		str			=torch.load(lowerCamelCase     )

														# Legacy cache files have only features, while new cache files
														# will have dataset and examples also.
														lowerCamelCase__		:		int			=self.old_features['''features''']
														lowerCamelCase__		:		Optional[int]			=self.old_features.get('''dataset''',  lowerCamelCase     )
														lowerCamelCase__		:		int			=self.old_features.get('''examples''',  lowerCamelCase     )
														logger.info(
														    F'''Loading features from cached file {cached_features_file} [took %.3f s]''',  time.time() - start     )

														if self.dataset is None or self.examples is None:
																	logger.warning(
																	    F'''Deleting cached file {cached_features_file} will allow dataset and examples to be cached in'''
																	    ''' future run'''     )
											else:
														if mode == Split.dev:
																	lowerCamelCase__		:		Tuple			=self.processor.get_dev_examples(args.data_dir     )
														else:
																	lowerCamelCase__		:		Optional[int]			=self.processor.get_train_examples(args.data_dir     )

														lowerCamelCase__	,   lowerCamelCase__		:		List[str]			=squad_convert_examples_to_features(
														    examples=self.examples,  tokenizer=lowerCamelCase,  max_seq_length=args.max_seq_length,  doc_stride=args.doc_stride,  max_query_length=args.max_query_length,  is_training=mode == Split.train,  threads=args.threads,  return_dataset=lowerCamelCase,  )

														lowerCamelCase__		:		List[str]			=time.time()
														torch.save(
														    {'''features''': self.features, '''dataset''': self.dataset, '''examples''': self.examples},  lowerCamelCase,  )
														# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
														logger.info(
														    F'''Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]'''     )



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




					def __getitem__(       self							:  List[str],  lowerCamelCase							:  List[Any]     )->					Dict[str, torch.Tensor]:
								# Convert to Tensors and build dataset
								lowerCamelCase__		:		List[Any]			=self.features[i]

								lowerCamelCase__		:		List[Any]			=torch.tensor(feature.input_ids,  dtype=torch.long     )
								lowerCamelCase__		:		List[str]			=torch.tensor(feature.attention_mask,  dtype=torch.long     )
								lowerCamelCase__		:		List[Any]			=torch.tensor(feature.token_type_ids,  dtype=torch.long     )
								lowerCamelCase__		:		Optional[int]			=torch.tensor(feature.cls_index,  dtype=torch.long     )
								lowerCamelCase__		:		Optional[int]			=torch.tensor(feature.p_mask,  dtype=torch.float     )
								lowerCamelCase__		:		List[Any]			=torch.tensor(feature.is_impossible,  dtype=torch.float     )

								lowerCamelCase__		:		Optional[Any]			={
								    '''input_ids''': input_ids,
								    '''attention_mask''': attention_mask,
								    '''token_type_ids''': token_type_ids,
								}

								if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
											del inputs["token_type_ids"]

								if self.args.model_type in ["xlnet", "xlm"]:
											inputs.update({'''cls_index''': cls_index, '''p_mask''': p_mask}     )
											if self.args.version_2_with_negative:
														inputs.update({'''is_impossible''': is_impossible}     )
											if self.is_language_sensitive:
														inputs.update({'''langs''': (torch.ones(input_ids.shape,  dtype=torch.intaa     ) * self.args.lang_id)}     )

								if self.mode == Split.train:
											lowerCamelCase__		:		str			=torch.tensor(feature.start_position,  dtype=torch.long     )
											lowerCamelCase__		:		int			=torch.tensor(feature.end_position,  dtype=torch.long     )
											inputs.update({'''start_positions''': start_positions, '''end_positions''': end_positions}     )

								return inputs




