




import warnings
from dataclasses import dataclass, field
from typing import Optional, Tuple

from .training_args import TrainingArguments
from .utils import cached_property, is_tf_available, logging, requires_backends


lowercase__   :    Dict 					=      logging.get_logger(__name__)

if is_tf_available():
			import tensorflow as tf




@dataclass
class     a__ (      lowercase__   ):
					a	:    Optional[Any]	      =			"""tf"""
					a	:    Optional[str]	      =			field(
					    default=lowercase__     ,      metadata={"""help""": """Name of TPU"""}     ,      )

					a	:    Optional[str]	      =			field(
					    default=lowercase__     ,      metadata={"""help""": """Zone of TPU"""}     ,      )

					a	:    Optional[str]	      =			field(
					    default=lowercase__     ,      metadata={"""help""": """Name of Cloud TPU-enabled project"""}     ,      )

					a	:    float	      =			field(
					    default=1.0     ,      metadata={"""help""": """Power for the Polynomial decay LR scheduler."""}     ,      )

					a	:    bool	      =			field(default=lowercase__     ,      metadata={"""help""": """Whether to activate the XLA compilation or not"""}   )







					@cached_property
					def     lowerCAmelCase_       (			self				)						->					Tuple["tf.distribute.Strategy", int]:



										'''simple docstring'''



										requires_backends(self						,	["tf"]				)
										logger.info("Tensorflow: setting up strategy"				)

										a											=   tf.config.list_physical_devices("GPU"				)

										# Set to float16 at first
										if self.fpaa:
															tf.keras.mixed_precision.set_global_policy("mixed_float16"				)

										if self.no_cuda:
															a											=   tf.distribute.OneDeviceStrategy(device="/cpu:0"				)
										else:
															try:
																				if self.tpu_name:
																									a											=   tf.distribute.cluster_resolver.TPUClusterResolver(
																									    self.tpu_name						,	zone=self.tpu_zone						,	project=self.gcp_project				)
																				else:
																									a											=   tf.distribute.cluster_resolver.TPUClusterResolver()
															except ValueError:
																				if self.tpu_name:
																									raise RuntimeError(F'''Couldn\'t connect to TPU {self.tpu_name}!'''				)
																				else:
																									a											=   None

															if tpu:
																				# Set to bfloat16 in case of TPU
																				if self.fpaa:
																									tf.keras.mixed_precision.set_global_policy("mixed_bfloat16"				)

																				tf.config.experimental_connect_to_cluster(_A				)
																				tf.tpu.experimental.initialize_tpu_system(_A				)

																				a											=   tf.distribute.TPUStrategy(_A				)

															elif len(_A				) == 0:
																				a											=   tf.distribute.OneDeviceStrategy(device="/cpu:0"				)
															elif len(_A				) == 1:
																				a											=   tf.distribute.OneDeviceStrategy(device="/gpu:0"				)
															elif len(_A				) > 1:
																				# If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
																				a											=   tf.distribute.MirroredStrategy()
															else:
																				raise ValueError("Cannot find the proper strategy, please check your environment properties."				)

										return strategy







					@property
					def     lowerCAmelCase_       (			self				)						->					"tf.distribute.Strategy":



										'''simple docstring'''



										requires_backends(self						,	["tf"]				)
										return self._setup_strategy







					@property
					def     lowerCAmelCase_       (			self				)						->					int:



										'''simple docstring'''



										requires_backends(self						,	["tf"]				)
										return self._setup_strategy.num_replicas_in_sync







					@property
					def     lowerCAmelCase_       (			self				)						->					List[str]:



										'''simple docstring'''



										return False  # TF Logging is handled by Keras not the Trainer







					@property
					def     lowerCAmelCase_       (			self				)						->					int:



										'''simple docstring'''



										if self.per_gpu_train_batch_size:
															logger.warning(
															    "Using deprecated `--per_gpu_train_batch_size` argument which will be removed in a future "
															    "version. Using `--per_device_train_batch_size` is preferred."				)
										a											=   self.per_gpu_train_batch_size or self.per_device_train_batch_size
										return per_device_batch_size * self.n_replicas







					@property
					def     lowerCAmelCase_       (			self				)						->					int:



										'''simple docstring'''



										if self.per_gpu_eval_batch_size:
															logger.warning(
															    "Using deprecated `--per_gpu_eval_batch_size` argument which will be removed in a future "
															    "version. Using `--per_device_eval_batch_size` is preferred."				)
										a											=   self.per_gpu_eval_batch_size or self.per_device_eval_batch_size
										return per_device_batch_size * self.n_replicas







					@property
					def     lowerCAmelCase_       (			self				)						->					int:



										'''simple docstring'''



										requires_backends(self						,	["tf"]				)
										warnings.warn(
										    "The n_gpu argument is deprecated and will be removed in a future version, use n_replicas instead."						,	_A						,	)
										return self._setup_strategy.num_replicas_in_sync







from sklearn.metrics import mean_absolute_error

import datasets


lowercase__   :    int 					=      "\\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n"

lowercase__   :    str 					=      "\\nMean Absolute Error (MAE) is the mean of the magnitude of difference between the predicted and actual\nvalues.\n"


lowercase__   :    Tuple 					=      "\nArgs:\n    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)\n        Estimated target values.\n    references: array-like of shape (n_samples,) or (n_samples, n_outputs)\n        Ground truth (correct) target values.\n    sample_weight: array-like of shape (n_samples,), default=None\n        Sample weights.\n    multioutput: {\"raw_values\", \"uniform_average\"} or array-like of shape (n_outputs,), default=\"uniform_average\"\n        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.\n\n                 \"raw_values\" : Returns a full set of errors in case of multioutput input.\n\n                 \"uniform_average\" : Errors of all outputs are averaged with uniform weight.\n\nReturns:\n    mae : mean absolute error.\n        If multioutput is \"raw_values\", then mean absolute error is returned for each output separately. If multioutput is \"uniform_average\" or an ndarray of weights, then the weighted average of all output errors is returned.\n        MAE output is non-negative floating point. The best value is 0.0.\nExamples:\n\n    >>> mae_metric = datasets.load_metric(\"mae\")\n    >>> predictions = [2.5, 0.0, 2, 8]\n    >>> references = [3, -0.5, 2, 7]\n    >>> results = mae_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'mae': 0.5}\n\n    If you're using multi-dimensional lists, then set the config as follows :\n\n    >>> mae_metric = datasets.load_metric(\"mae\", \"multilist\")\n    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]\n    >>> references = [[0, 2], [-1, 2], [8, -5]]\n    >>> results = mae_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'mae': 0.75}\n    >>> results = mae_metric.compute(predictions=predictions, references=references, multioutput='raw_values')\n    >>> print(results)\n    {'mae': array([0.5, 1. ])}\n"




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,      _KWARGS_DESCRIPTION   )
class     a__ (      datasets.Metric   ):







     def     lowerCAmelCase_       (			self				)						->					Dict:



          '''simple docstring'''



          return datasets.MetricInfo(
              description=_DESCRIPTION						,	citation=_CITATION						,	inputs_description=_KWARGS_DESCRIPTION						,	features=datasets.Features(self._get_feature_types()				)						,	reference_urls=[
                  "https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_absolute_error.html"
              ]						,	)







     def     lowerCAmelCase_       (			self				)						->					Tuple:



          '''simple docstring'''



          if self.config_name == "multilist":
               return {
                   "predictions": datasets.Sequence(datasets.Value("float"				)				),
                   "references": datasets.Sequence(datasets.Value("float"				)				),
               }
          else:
               return {
                   "predictions": datasets.Value("float"				),
                   "references": datasets.Value("float"				),
               }







     def     lowerCAmelCase_       (			self						,	A						,	A						,	A=None						,	A="uniform_average"				)						->					List[Any]:



          '''simple docstring'''



          a											=   mean_absolute_error(A						,	A						,	sample_weight=A						,	multioutput=A				)

          return {"mae": mae_score}

