
from typing import Dict

from transformers import EvalPrediction, HfArgumentParser, TrainingArguments, is_torch_available
from transformers.testing_utils import (
    TestCasePlus,
    execute_subprocess_async,
    get_torch_dist_unique_port,
    require_torch_multi_gpu,
    require_torch_neuroncore,
)
from transformers.training_args import ParallelMode
from transformers.utils import logging


lowerCamelCase__     :		Tuple        = logging.get_logger(__name__)


if is_torch_available():
     import torch
     from torch import nn
     from torch.utils.data import Dataset

     from transformers import Trainer



     class    _snake_case (						UpperCAmelCase_				):


      def __init__(       self       ,	SCREAMING_SNAKE_CASE_ = 1_01):


        '''simple docstring'''




        lowercase__	: Dict     		=   length


      def __len__(       self):


        '''simple docstring'''




        return self.length



      def __getitem__(       self       ,	SCREAMING_SNAKE_CASE_):


        '''simple docstring'''




        return i



     class    _snake_case :


      def __call__(       self       ,	SCREAMING_SNAKE_CASE_):


        '''simple docstring'''




        return {"input_ids": torch.tensor(SCREAMING_SNAKE_CASE_), "labels": torch.tensor(SCREAMING_SNAKE_CASE_)}



     class    _snake_case (						nn.Module				):


      def __init__(       self):


        '''simple docstring'''




        super().__init__()
        # Add some (unused) params otherwise DDP will complain.
        lowercase__	: Optional[Any]     		=   nn.Linear(1_20       ,	80)



      def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_=None):


        '''simple docstring'''




        if labels is not None:
          return torch.tensor(0.0       ,	device=input_ids.device), input_ids
        else:
          return input_ids



class    _snake_case (						UpperCAmelCase_				):


 @require_torch_neuroncore
 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: str     		=   f'--nproc_per_node=2\n            --master_port={get_torch_dist_unique_port()}\n            {self.test_file_dir}/test_trainer_distributed.py\n        '.split()
   lowercase__	: Any     		=   self.get_auto_remove_tmp_dir()
   lowercase__	: Optional[int]     		=   f'--output_dir {output_dir}'.split()
   lowercase__	: Union[str, Any]     		=   ["""torchrun"""] + distributed_args + args
   execute_subprocess_async(SCREAMING_SNAKE_CASE_       ,	env=self.get_env())
   # successful return here == success - any errors would have caused an error in the sub-call



class    _snake_case (						UpperCAmelCase_				):


 @require_torch_multi_gpu
 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: str     		=   f'--nproc_per_node={torch.cuda.device_count()}\n            --master_port={get_torch_dist_unique_port()}\n            {self.test_file_dir}/test_trainer_distributed.py\n        '.split()
   lowercase__	: List[str]     		=   self.get_auto_remove_tmp_dir()
   lowercase__	: Dict     		=   f'--output_dir {output_dir}'.split()
   lowercase__	: List[str]     		=   ["""torchrun"""] + distributed_args + args
   execute_subprocess_async(SCREAMING_SNAKE_CASE_       ,	env=self.get_env())
   # successful return here == success - any errors would have caused an error in the sub-call


if __name__ == "__main__":
     # The script below is meant to be run under torch.distributed, on a machine with multiple GPUs:
     #
     # PYTHONPATH="src" python -m torch.distributed.run --nproc_per_node 2 --output_dir output_dir ./tests/test_trainer_distributed.py

     lowerCamelCase__     :		List[Any]        = HfArgumentParser((TrainingArguments,))
     lowerCamelCase__     :		Optional[Any]        = parser.parse_args_into_dataclasses()[0]

     logger.warning(
         f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, '''
         f'''distributed training: {training_args.parallel_mode != ParallelMode.NOT_DISTRIBUTED}'''
     )

     # Essentially, what we want to verify in the distributed case is that we get all samples back,
     # in the right order. (this is crucial for prediction for instance)
     for dataset_length in [1_0_1, 4_0, 7]:
          lowerCamelCase__     :		Tuple        = DummyDataset(dataset_length)

          def 		UpperCamelCase						(   lowercase_ )		->						Dict:


            '''simple docstring'''






            lowercase__	: Dict     		=   list(range(len(lowercase_ ) ) )
            lowercase__	: Union[str, Any]     		=   p.predictions.tolist() == sequential and p.label_ids.tolist() == sequential
            if not success and training_args.local_rank == 0:
              logger.warning(
                  """Predictions and/or labels do not match expected results:\n  - predictions: """
                  F'{p.predictions.tolist()}\n  - labels: {p.label_ids.tolist()}\n  - expected: {sequential}' )
            return {"success": success}

          lowerCamelCase__     :		Optional[int]        = Trainer(
              model=DummyModel(),
              args=training_args,
              data_collator=DummyDataCollator(),
              eval_dataset=dataset,
              compute_metrics=compute_metrics,
          )
          lowerCamelCase__     :		List[Any]        = trainer.evaluate()
          logger.info(metrics)
          if metrics["eval_success"] is not True:
               logger.error(metrics)
               exit(1)

          lowerCamelCase__     :		str        = trainer.predict(dataset)
          logger.info(p.metrics)
          if p.metrics["test_success"] is not True:
               logger.error(p.metrics)
               exit(1)

          lowerCamelCase__     :		str        = 2

          lowerCamelCase__     :		str        = trainer.evaluate()
          logger.info(metrics)
          if metrics["eval_success"] is not True:
               logger.error(metrics)
               exit(1)

          lowerCamelCase__     :		Any        = trainer.predict(dataset)
          logger.info(p.metrics)
          if p.metrics["test_success"] is not True:
               logger.error(p.metrics)
               exit(1)



          lowerCamelCase__     :		List[Any]        = None








# 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 argparse

from ...utils.dataclasses import (
    ComputeEnvironment,
    DistributedType,
    DynamoBackend,
    PrecisionType,
    SageMakerDistributedType,
)
from ..menu import BulletMenu


lowerCamelCase__     :		Optional[int]        = [
    """EAGER""",
    """AOT_EAGER""",
    """INDUCTOR""",
    """NVFUSER""",
    """AOT_NVFUSER""",
    """AOT_CUDAGRAPHS""",
    """OFI""",
    """FX2TRT""",
    """ONNXRT""",
    """IPEX""",
]

def 		UpperCamelCase						(   lowercase_			,			lowercase_=None			,			lowercase_=None			,			lowercase_=None )		->						Optional[Any]:


  '''simple docstring'''






  lowercase__	: List[Any]     		=   True
  while ask_again:
    lowercase__	: Tuple     		=   input(lowercase_ )
    try:
      if default is not None and len(lowercase_ ) == 0:
        return default
      return convert_value(lowercase_ ) if convert_value is not None else result
    except Exception:
      if error_message is not None:
        print(lowercase_ )

def 		UpperCamelCase						(   lowercase_			,			lowercase_=[]			,			lowercase_=None			,			lowercase_=0 )		->						Union[str, Any]:


  '''simple docstring'''






  lowercase__	: List[Any]     		=   BulletMenu(lowercase_			,			lowercase_ )
  lowercase__	: Any     		=   menu.run(default_choice=lowercase_ )
  return convert_value(lowercase_ ) if convert_value is not None else result

def 		UpperCamelCase						(   lowercase_ )		->						str:


  '''simple docstring'''






  lowercase__	: Union[str, Any]     		=   int(lowercase_ )
  return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] )

def 		UpperCamelCase						(   lowercase_ )		->						Optional[int]:


  '''simple docstring'''






  lowercase__	: List[str]     		=   int(lowercase_ )
  return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] )

def 		UpperCamelCase						(   lowercase_ )		->						str:


  '''simple docstring'''






  lowercase__	: str     		=   int(lowercase_ )
  return DynamoBackend(DYNAMO_BACKENDS[value] ).value

def 		UpperCamelCase						(   lowercase_ )		->						Union[str, Any]:


  '''simple docstring'''






  lowercase__	: List[Any]     		=   int(lowercase_ )
  return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] )

def 		UpperCamelCase						(   lowercase_ )		->						Optional[int]:


  '''simple docstring'''






  lowercase__	: List[Any]     		=   int(lowercase_ )
  return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] )

def 		UpperCamelCase						(   lowercase_ )		->						Optional[int]:


  '''simple docstring'''






  return {"yes": True, "no": False}[value.lower()]



class    _snake_case (						argparse.RawDescriptionHelpFormatter				):


 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__	: int     		=   super()._format_usage(SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_)
   lowercase__	: Optional[Any]     		=   usage.replace("""<command> [<args>] """       ,	"""""")
   return usage






