

'''simple docstring'''
import argparse
import ast
import logging
import os
import sys

import pandas as pd
import torch
from tqdm import tqdm

from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration
from transformers import logging as transformers_logging


sys.path.append(os.path.join(os.getcwd()))  # noqa: E402 # isort:skip
from utils_rag import exact_match_score, fa_score  # noqa: E402 # isort:skip


lowerCamelCase :      Any					 =     logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

transformers_logging.set_verbosity_info()


def        _lowerCAmelCase					(						_UpperCamelCase						:     Optional[Any]				)      ->			List[str]:
     """simple docstring"""




     if "token" in model_name_or_path:
          return "rag_token"
     if "sequence" in model_name_or_path:
          return "rag_sequence"
     if "bart" in model_name_or_path:
          return "bart"
     return None


def        _lowerCAmelCase					(						_UpperCamelCase						:     int							, _UpperCamelCase						:     int							, _UpperCamelCase						:     str				)      ->			Tuple:
     """simple docstring"""




     return max(metric_fn(_UpperCamelCase							, _UpperCamelCase				) for gt in ground_truths				)


def        _lowerCAmelCase					(						_UpperCamelCase						:     List[str]							, _UpperCamelCase						:     int							, _UpperCamelCase						:     List[str]				)      ->			Tuple:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							    =[line.strip() for line in open(_UpperCamelCase							, 'r'				).readlines()]
     _SCREAMING_SNAKE_CASE							    =[]

     if args.gold_data_mode == "qa":
          _SCREAMING_SNAKE_CASE							    =pd.read_csv(_UpperCamelCase							, sep='\t'							, header=_UpperCamelCase				)
          for answer_list in data[1]:
               _SCREAMING_SNAKE_CASE							    =ast.literal_eval(_UpperCamelCase				)
               answers.append(_UpperCamelCase				)
     else:
          _SCREAMING_SNAKE_CASE							    =[line.strip() for line in open(_UpperCamelCase							, 'r'				).readlines()]
          _SCREAMING_SNAKE_CASE							    =[[reference] for reference in references]

     _SCREAMING_SNAKE_CASE							    =_SCREAMING_SNAKE_CASE							    =_SCREAMING_SNAKE_CASE							    =0
     for prediction, ground_truths in zip(_UpperCamelCase							, _UpperCamelCase				):
          total += 1
          em += metric_max_over_ground_truths(_UpperCamelCase							, _UpperCamelCase							, _UpperCamelCase				)
          fa += metric_max_over_ground_truths(_UpperCamelCase							, _UpperCamelCase							, _UpperCamelCase				)

     _SCREAMING_SNAKE_CASE							    =1_00.0 * em / total
     _SCREAMING_SNAKE_CASE							    =1_00.0 * fa / total

     logger.info(f"F1: {fa:.2f}"				)
     logger.info(f"EM: {em:.2f}"				)


def        _lowerCAmelCase					(						_UpperCamelCase						:     Union[str, Any]							, _UpperCamelCase						:     Dict							, _UpperCamelCase						:     List[str]				)      ->			Optional[Any]:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							    =args.k
     _SCREAMING_SNAKE_CASE							    =[line.strip() for line in open(_UpperCamelCase							, 'r'				).readlines()]
     _SCREAMING_SNAKE_CASE							    =[line.strip() for line in open(_UpperCamelCase							, 'r'				).readlines()]

     _SCREAMING_SNAKE_CASE							    =_SCREAMING_SNAKE_CASE							    =0
     for hypo, reference in zip(_UpperCamelCase							, _UpperCamelCase				):
          _SCREAMING_SNAKE_CASE							    =set(hypo.split('\t'				)[:k]				)
          _SCREAMING_SNAKE_CASE							    =set(reference.split('\t'				)				)
          total += 1
          em += len(hypo_provenance & ref_provenance				) / k

     _SCREAMING_SNAKE_CASE							    =1_00.0 * em / total
     logger.info(f"Precision@{k}: {em: .2f}"				)


def        _lowerCAmelCase					(						_UpperCamelCase						:     str							, _UpperCamelCase						:     Any							, _UpperCamelCase						:     Optional[int]				)      ->			List[Any]:
     """simple docstring"""




     def strip_title(_UpperCamelCase						:     Optional[Any]				):
          if title.startswith('"'				):
               _SCREAMING_SNAKE_CASE							    =title[1:]
          if title.endswith('"'				):
               _SCREAMING_SNAKE_CASE							    =title[:-1]
          return title

     _SCREAMING_SNAKE_CASE							    =rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
         _UpperCamelCase							, return_tensors='pt'							, padding=_UpperCamelCase							, truncation=_UpperCamelCase							, )['input_ids'].to(args.device				)

     _SCREAMING_SNAKE_CASE							    =rag_model.rag.question_encoder(_UpperCamelCase				)
     _SCREAMING_SNAKE_CASE							    =question_enc_outputs[0]

     _SCREAMING_SNAKE_CASE							    =rag_model.retriever(
         _UpperCamelCase							, question_enc_pool_output.cpu().detach().to(torch.floataa				).numpy()							, prefix=rag_model.rag.generator.config.prefix							, n_docs=rag_model.config.n_docs							, return_tensors='pt'							, )
     _SCREAMING_SNAKE_CASE							    =rag_model.retriever.index.get_doc_dicts(result.doc_ids				)
     _SCREAMING_SNAKE_CASE							    =[]
     for docs in all_docs:
          _SCREAMING_SNAKE_CASE							    =[strip_title(_UpperCamelCase				) for title in docs['title']]
          provenance_strings.append('\t'.join(_UpperCamelCase				)				)
     return provenance_strings


def        _lowerCAmelCase					(						_UpperCamelCase						:     Tuple							, _UpperCamelCase						:     Union[str, Any]							, _UpperCamelCase						:     Optional[int]				)      ->			str:
     """simple docstring"""




     with torch.no_grad():
          _SCREAMING_SNAKE_CASE							    =rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
              _UpperCamelCase							, return_tensors='pt'							, padding=_UpperCamelCase							, truncation=_UpperCamelCase				)

          _SCREAMING_SNAKE_CASE							    =inputs_dict.input_ids.to(args.device				)
          _SCREAMING_SNAKE_CASE							    =inputs_dict.attention_mask.to(args.device				)
          _SCREAMING_SNAKE_CASE							    =rag_model.generate(  # rag_model overwrites generate
              _UpperCamelCase							, attention_mask=_UpperCamelCase							, num_beams=args.num_beams							, min_length=args.min_length							, max_length=args.max_length							, early_stopping=_UpperCamelCase							, num_return_sequences=1							, bad_words_ids=[[0, 0]]							, )
          _SCREAMING_SNAKE_CASE							    =rag_model.retriever.generator_tokenizer.batch_decode(_UpperCamelCase							, skip_special_tokens=_UpperCamelCase				)

          if args.print_predictions:
               for q, a in zip(_UpperCamelCase							, _UpperCamelCase				):
                    logger.info('Q: {} - A: {}'.format(_UpperCamelCase							, _UpperCamelCase				)				)

          return answers


def        _lowerCAmelCase					(						)      ->			int:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							    =argparse.ArgumentParser()
     parser.add_argument(
         '--model_type'							, choices=['rag_sequence', 'rag_token', 'bart']							, type=_UpperCamelCase							, help=(
             'RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the'
             ' model_name_or_path'
         )							, )
     parser.add_argument(
         '--index_name'							, default=_UpperCamelCase							, choices=['exact', 'compressed', 'legacy']							, type=_UpperCamelCase							, help='RAG model retriever type'							, )
     parser.add_argument(
         '--index_path'							, default=_UpperCamelCase							, type=_UpperCamelCase							, help='Path to the retrieval index'							, )
     parser.add_argument('--n_docs'							, default=5							, type=_UpperCamelCase							, help='Number of retrieved docs'				)
     parser.add_argument(
         '--model_name_or_path'							, default=_UpperCamelCase							, type=_UpperCamelCase							, required=_UpperCamelCase							, help='Path to pretrained checkpoints or model identifier from huggingface.co/models'							, )
     parser.add_argument(
         '--eval_mode'							, choices=['e2e', 'retrieval']							, default='e2e'							, type=_UpperCamelCase							, help=(
             'Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates'
             ' precision@k.'
         )							, )
     parser.add_argument('--k'							, default=1							, type=_UpperCamelCase							, help='k for the precision@k calculation'				)
     parser.add_argument(
         '--evaluation_set'							, default=_UpperCamelCase							, type=_UpperCamelCase							, required=_UpperCamelCase							, help='Path to a file containing evaluation samples'							, )
     parser.add_argument(
         '--gold_data_path'							, default=_UpperCamelCase							, type=_UpperCamelCase							, required=_UpperCamelCase							, help='Path to a tab-separated file with gold samples'							, )
     parser.add_argument(
         '--gold_data_mode'							, default='qa'							, type=_UpperCamelCase							, choices=['qa', 'ans']							, help=(
             'Format of the gold data file'
             'qa - a single line in the following format: question [tab] answer_list'
             'ans - a single line of the gold file contains the expected answer string'
         )							, )
     parser.add_argument(
         '--predictions_path'							, type=_UpperCamelCase							, default='predictions.txt'							, help='Name of the predictions file, to be stored in the checkpoints directory'							, )
     parser.add_argument(
         '--eval_all_checkpoints'							, action='store_true'							, help='Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number'							, )
     parser.add_argument(
         '--eval_batch_size'							, default=8							, type=_UpperCamelCase							, help='Batch size per GPU/CPU for evaluation.'							, )
     parser.add_argument(
         '--recalculate'							, help='Recalculate predictions even if the prediction file exists'							, action='store_true'							, )
     parser.add_argument(
         '--num_beams'							, default=4							, type=_UpperCamelCase							, help='Number of beams to be used when generating answers'							, )
     parser.add_argument('--min_length'							, default=1							, type=_UpperCamelCase							, help='Min length of the generated answers'				)
     parser.add_argument('--max_length'							, default=50							, type=_UpperCamelCase							, help='Max length of the generated answers'				)

     parser.add_argument(
         '--print_predictions'							, action='store_true'							, help='If True, prints predictions while evaluating.'							, )
     parser.add_argument(
         '--print_docs'							, action='store_true'							, help='If True, prints docs retried while generating.'							, )
     _SCREAMING_SNAKE_CASE							    =parser.parse_args()
     _SCREAMING_SNAKE_CASE							    =torch.device('cuda' if torch.cuda.is_available() else 'cpu'				)
     return args


def        _lowerCAmelCase					(						_UpperCamelCase						:     List[Any]				)      ->			Optional[Any]:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							    ={}
     if args.model_type is None:
          _SCREAMING_SNAKE_CASE							    =infer_model_type(args.model_name_or_path				)
          assert args.model_type is not None
     if args.model_type.startswith('rag'				):
          _SCREAMING_SNAKE_CASE							    =RagTokenForGeneration if args.model_type == 'rag_token' else RagSequenceForGeneration
          _SCREAMING_SNAKE_CASE							    =args.n_docs
          if args.index_name is not None:
               _SCREAMING_SNAKE_CASE							    =args.index_name
          if args.index_path is not None:
               _SCREAMING_SNAKE_CASE							    =args.index_path
     else:
          _SCREAMING_SNAKE_CASE							    =BartForConditionalGeneration

     _SCREAMING_SNAKE_CASE							    =(
         [f.path for f in os.scandir(args.model_name_or_path				) if f.is_dir()]
         if args.eval_all_checkpoints
         else [args.model_name_or_path]
     )

     logger.info('Evaluate the following checkpoints: %s'							, _UpperCamelCase				)

     _SCREAMING_SNAKE_CASE							    =get_scores if args.eval_mode == 'e2e' else get_precision_at_k
     _SCREAMING_SNAKE_CASE							    =evaluate_batch_eae if args.eval_mode == 'e2e' else evaluate_batch_retrieval

     for checkpoint in checkpoints:
          if os.path.exists(args.predictions_path				) and (not args.recalculate):
               logger.info('Calculating metrics based on an existing predictions file: {}'.format(args.predictions_path				)				)
               score_fn(_UpperCamelCase							, args.predictions_path							, args.gold_data_path				)
               continue

          logger.info('***** Running evaluation for {} *****'.format(_UpperCamelCase				)				)
          logger.info('  Batch size = %d'							, args.eval_batch_size				)
          logger.info('  Predictions will be stored under {}'.format(args.predictions_path				)				)

          if args.model_type.startswith('rag'				):
               _SCREAMING_SNAKE_CASE							    =RagRetriever.from_pretrained(_UpperCamelCase							, **_UpperCamelCase				)
               _SCREAMING_SNAKE_CASE							    =model_class.from_pretrained(_UpperCamelCase							, retriever=_UpperCamelCase							, **_UpperCamelCase				)
               model.retriever.init_retrieval()
          else:
               _SCREAMING_SNAKE_CASE							    =model_class.from_pretrained(_UpperCamelCase							, **_UpperCamelCase				)
          model.to(args.device				)

          with open(args.evaluation_set							, 'r'				) as eval_file, open(args.predictions_path							, 'w'				) as preds_file:
               _SCREAMING_SNAKE_CASE							    =[]
               for line in tqdm(_UpperCamelCase				):
                    questions.append(line.strip()				)
                    if len(_UpperCamelCase				) == args.eval_batch_size:
                         _SCREAMING_SNAKE_CASE							    =evaluate_batch_fn(_UpperCamelCase							, _UpperCamelCase							, _UpperCamelCase				)
                         preds_file.write('\n'.join(_UpperCamelCase				) + '\n'				)
                         preds_file.flush()
                         _SCREAMING_SNAKE_CASE							    =[]
               if len(_UpperCamelCase				) > 0:
                    _SCREAMING_SNAKE_CASE							    =evaluate_batch_fn(_UpperCamelCase							, _UpperCamelCase							, _UpperCamelCase				)
                    preds_file.write('\n'.join(_UpperCamelCase				)				)
                    preds_file.flush()

               score_fn(_UpperCamelCase							, args.predictions_path							, args.gold_data_path				)


if __name__ == "__main__":
     lowerCamelCase :      List[str]					 =     get_args()
     main(args)



'''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        _lowerCAmelCase					(						_UpperCamelCase						:     Optional[int]				)      ->			List[str]:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							    =botoa.client('iam'				)

     _SCREAMING_SNAKE_CASE							    ={
         '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=_UpperCamelCase							, AssumeRolePolicyDocument=json.dumps(_UpperCamelCase							, indent=2				)				)
          _SCREAMING_SNAKE_CASE							    ={
              '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=_UpperCamelCase							, PolicyName=f"{role_name}_policy_permission"							, PolicyDocument=json.dumps(_UpperCamelCase							, indent=2				)							, )
     except iam_client.exceptions.EntityAlreadyExistsException:
          print(f"role {role_name} already exists. Using existing one"				)


def        _lowerCAmelCase					(						_UpperCamelCase						:     List[str]				)      ->			Optional[int]:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							    =botoa.client('iam'				)
     return iam_client.get_role(RoleName=_UpperCamelCase				)["Role"]["Arn"]







def        _lowerCAmelCase					(						)      ->			Optional[int]:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							    =_ask_options(
         'How do you want to authorize?'							, ['AWS Profile', 'Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) ']							, _UpperCamelCase							, )
     _SCREAMING_SNAKE_CASE							    =None
     if credentials_configuration == 0:
          _SCREAMING_SNAKE_CASE							    =_ask_field('Enter your AWS Profile name: [default] '							, default='default'				)
          _SCREAMING_SNAKE_CASE							    =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							    =_ask_field('AWS Access Key ID: '				)
          _SCREAMING_SNAKE_CASE							    =aws_access_key_id

          _SCREAMING_SNAKE_CASE							    =_ask_field('AWS Secret Access Key: '				)
          _SCREAMING_SNAKE_CASE							    =aws_secret_access_key

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

     _SCREAMING_SNAKE_CASE							    =_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']							, _UpperCamelCase							, )
     if role_management == 0:
          _SCREAMING_SNAKE_CASE							    =_ask_field('Enter your IAM role name: '				)
     else:
          _SCREAMING_SNAKE_CASE							    ='accelerate_sagemaker_execution_role'
          print(f"Accelerate will create an iam role \"{iam_role_name}\" using the provided credentials"				)
          _create_iam_role_for_sagemaker(_UpperCamelCase				)

     _SCREAMING_SNAKE_CASE							    =_ask_field(
         'Do you want to use custom Docker image? [yes/NO]: '							, _convert_yes_no_to_bool							, default=_UpperCamelCase							, error_message='Please enter yes or no.'							, )
     _SCREAMING_SNAKE_CASE							    =None
     if is_custom_docker_image:
          _SCREAMING_SNAKE_CASE							    =_ask_field('Enter your Docker image: '							, lambda _UpperCamelCase				: str(_UpperCamelCase				).lower()				)

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

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

     _SCREAMING_SNAKE_CASE							    =_ask_options(
         'What is the distributed mode?'							, ['No distributed training', 'Data parallelism']							, _convert_sagemaker_distributed_mode							, )
     _SCREAMING_SNAKE_CASE							    ={}
     _SCREAMING_SNAKE_CASE							    =_ask_field(
         'Do you wish to optimize your script with torch dynamo?[yes/NO]:'							, _convert_yes_no_to_bool							, default=_UpperCamelCase							, error_message='Please enter yes or no.'							, )
     if use_dynamo:
          _SCREAMING_SNAKE_CASE							    ='dynamo_'
          _SCREAMING_SNAKE_CASE							    =_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							    =_ask_field(
              'Do you want to customize the defaults sent to torch.compile? [yes/NO]: '							, _convert_yes_no_to_bool							, default=_UpperCamelCase							, error_message='Please enter yes or no.'							, )

          if use_custom_options:
               _SCREAMING_SNAKE_CASE							    =_ask_options(
                   'Which mode do you want to use?'							, _UpperCamelCase							, lambda _UpperCamelCase				: TORCH_DYNAMO_MODES[int(_UpperCamelCase				)]							, default='default'							, )
               _SCREAMING_SNAKE_CASE							    =_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=_UpperCamelCase							, error_message='Please enter yes or no.'							, )
               _SCREAMING_SNAKE_CASE							    =_ask_field(
                   'Do you want to enable dynamic shape tracing? [yes/NO]: '							, _convert_yes_no_to_bool							, default=_UpperCamelCase							, error_message='Please enter yes or no.'							, )
     _SCREAMING_SNAKE_CASE							    ='Which EC2 instance type you want to use for your training?'
     if distributed_type != SageMakerDistributedType.NO:
          _SCREAMING_SNAKE_CASE							    =_ask_options(
              _UpperCamelCase							, _UpperCamelCase							, lambda _UpperCamelCase				: SAGEMAKER_PARALLEL_EC2_INSTANCES[int(_UpperCamelCase				)]				)
     else:
          eca_instance_query += "? [ml.p3.2xlarge]:"
          _SCREAMING_SNAKE_CASE							    =_ask_field(_UpperCamelCase							, lambda _UpperCamelCase				: str(_UpperCamelCase				).lower()							, default='ml.p3.2xlarge'				)

     _SCREAMING_SNAKE_CASE							    =1
     if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL):
          _SCREAMING_SNAKE_CASE							    =_ask_field(
              'How many machines do you want use? [1]: '							, _UpperCamelCase							, default=1							, )

     _SCREAMING_SNAKE_CASE							    =_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=_UpperCamelCase							, compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER							, distributed_type=_UpperCamelCase							, use_cpu=_UpperCamelCase							, dynamo_config=_UpperCamelCase							, eca_instance_type=_UpperCamelCase							, profile=_UpperCamelCase							, region=_UpperCamelCase							, iam_role_name=_UpperCamelCase							, mixed_precision=_UpperCamelCase							, num_machines=_UpperCamelCase							, sagemaker_inputs_file=_UpperCamelCase							, sagemaker_metrics_file=_UpperCamelCase							, )
