





'''simple docstring'''


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_   :   Optional[Any]       =					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       UpperCamelCase__  (		__lowerCAmelCase     ):







			def __init__(				self			:   Tuple , lowerCamelCase			:   int = 1_0_1		):




						'''simple docstring'''
						a__     = length







			def __len__(				self			:   str		):




						'''simple docstring'''
						return self.length







			def __getitem__(				self			:   List[str] , lowerCamelCase			:   Any		):




						'''simple docstring'''
						return i






		class       UpperCamelCase__  :







			def __call__(				self			:   str , lowerCamelCase			:   int		):




						'''simple docstring'''
						return {"input_ids": torch.tensor(lowerCamelCase		), "labels": torch.tensor(lowerCamelCase		)}






		class       UpperCamelCase__  (		nn.Module     ):







			def __init__(				self			:   int		):




						'''simple docstring'''
						super().__init__()
						# Add some (unused) params otherwise DDP will complain.
						a__     = nn.Linear(1_2_0 , 8_0		)







			def 						__a   (				self			:   int , lowerCamelCase			:   Tuple , lowerCamelCase			:   List[str]=None		):




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






class       UpperCamelCase__  (		__lowerCAmelCase     ):







	@require_torch_neuroncore
	def 						__a   (				self			:   Optional[Any]		):




				'''simple docstring'''
				a__     = F'''--nproc_per_node=2
            --master_port={get_torch_dist_unique_port()}
            {self.test_file_dir}/test_trainer_distributed.py
        '''.split()
				a__     = self.get_auto_remove_tmp_dir()
				a__     = F'''--output_dir {output_dir}'''.split()
				a__     = ["torchrun"] + distributed_args + args
				execute_subprocess_async(lowerCamelCase , env=self.get_env()		)
				# successful return here == success - any errors would have caused an error in the sub-call






class       UpperCamelCase__  (		__lowerCAmelCase     ):







	@require_torch_multi_gpu
	def 						__a   (				self			:   Dict		):




				'''simple docstring'''
				a__     = F'''--nproc_per_node={torch.cuda.device_count()}
            --master_port={get_torch_dist_unique_port()}
            {self.test_file_dir}/test_trainer_distributed.py
        '''.split()
				a__     = self.get_auto_remove_tmp_dir()
				a__     = F'''--output_dir {output_dir}'''.split()
				a__     = ["torchrun"] + distributed_args + args
				execute_subprocess_async(lowerCamelCase , 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[str]       =					HfArgumentParser((TrainingArguments,))
		lowerCAmelCase_   :   List[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 [101, 40, 7]:
				lowerCAmelCase_   :   Optional[int]       =					DummyDataset(dataset_length)







				def    _lowerCamelCase  (__lowerCamelCase  :     EvalPrediction     )   ->    Dict:
							a__     = list(range(len(__lowerCamelCase     )     )     )
							a__     = 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_   :   Dict       =					Trainer(
				    model=DummyModel(),
				    args=training_args,
				    data_collator=DummyDataCollator(),
				    eval_dataset=dataset,
				    compute_metrics=compute_metrics,
				)
				lowerCAmelCase_   :   str       =					trainer.evaluate()
				logger.info(metrics)
				if metrics["eval_success"] is not True:
						logger.error(metrics)
						exit(1)

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

				lowerCAmelCase_   :   Optional[Any]       =					2

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

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




				lowerCAmelCase_   :   List[str]       =					None










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

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


lowerCAmelCase_   :   List[Any]       =					[
    "EAGER",
    "AOT_EAGER",
    "INDUCTOR",
    "NVFUSER",
    "AOT_NVFUSER",
    "AOT_CUDAGRAPHS",
    "OFI",
    "FX2TRT",
    "ONNXRT",
    "IPEX",
]







def    _lowerCamelCase  (__lowerCamelCase  :     Tuple					,  __lowerCamelCase  :     Tuple=None					,  __lowerCamelCase  :     Tuple=None					,  __lowerCamelCase  :     List[Any]=None     )   ->    Any:
			a__     = True
			while ask_again:
						a__     = input(__lowerCamelCase     )
						try:
									if default is not None and len(__lowerCamelCase     ) == 0:
												return default
									return convert_value(__lowerCamelCase     ) if convert_value is not None else result
						except Exception:
									if error_message is not None:
												print(__lowerCamelCase     )







def    _lowerCamelCase  (__lowerCamelCase  :     Dict					,  __lowerCamelCase  :     List[Any]=[]					,  __lowerCamelCase  :     str=None					,  __lowerCamelCase  :     List[Any]=0     )   ->    List[Any]:
			a__     = BulletMenu(__lowerCamelCase					,  __lowerCamelCase     )
			a__     = menu.run(default_choice=__lowerCamelCase     )
			return convert_value(__lowerCamelCase     ) if convert_value is not None else result







def    _lowerCamelCase  (__lowerCamelCase  :     Tuple     )   ->    Optional[Any]:
			a__     = int(__lowerCamelCase     )
			return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value]     )







def    _lowerCamelCase  (__lowerCamelCase  :     List[str]     )   ->    Optional[int]:
			a__     = int(__lowerCamelCase     )
			return DistributedType(["NO", "MULTI_CPU", "MULTI_XPU", "MULTI_GPU", "MULTI_NPU", "TPU"][value]     )







def    _lowerCamelCase  (__lowerCamelCase  :     List[Any]     )   ->    Optional[Any]:
			a__     = int(__lowerCamelCase     )
			return DynamoBackend(DYNAMO_BACKENDS[value]     ).value







def    _lowerCamelCase  (__lowerCamelCase  :     str     )   ->    str:
			a__     = int(__lowerCamelCase     )
			return PrecisionType(["no", "fp16", "bf16", "fp8"][value]     )







def    _lowerCamelCase  (__lowerCamelCase  :     int     )   ->    Optional[Any]:
			a__     = int(__lowerCamelCase     )
			return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value]     )







def    _lowerCamelCase  (__lowerCamelCase  :     Any     )   ->    List[Any]:
			return {"yes": True, "no": False}[value.lower()]






class       UpperCamelCase__  (		argparse.RawDescriptionHelpFormatter     ):







	def 						__a   (				self			:   Dict , lowerCamelCase			:   int , lowerCamelCase			:   Optional[Any] , lowerCamelCase			:   List[Any] , lowerCamelCase			:   Dict		):




				'''simple docstring'''
				a__     = super()._format_usage(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase		)
				a__     = usage.replace("<command> [<args>] " , ""		)
				return usage



