


'''simple docstring'''

# This test is meant to be run in on an instance with TPUs like this:
#
#   python examples/pytorch/xla_spawn.py --num_cores=8 tests/test_trainer_tpu.py
#
# Replace 8 with the number of TPU cores you have.
#

import sys
from typing import Dict

from transformers import EvalPrediction, HfArgumentParser, TrainingArguments, is_torch_available
from transformers.utils import logging


a_  :    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   (   lowercase      ):





       """simple docstring"""




       def __init__(   self      ,  UpperCamelCase = 101					):







        """simple docstring"""
        lowerCamelCase_								=  length






       def __len__(   self					):







        """simple docstring"""
        return self.length







       def __getitem__(   self      ,  UpperCamelCase					):







        """simple docstring"""
        return i





     class 					snake_case   :





       """simple docstring"""




       def __call__(   self      ,  UpperCamelCase					):







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





     class 					snake_case   (   nn.Module      ):





       """simple docstring"""




       def __init__(   self					):







        """simple docstring"""
        super().__init__()
        # Add some (unused) params otherwise DDP will complain.
        lowerCamelCase_								=  nn.Linear(120      ,  80					)







       def   snake_case		(   self      ,  UpperCamelCase      ,  UpperCamelCase=None					):







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





def __snake_case (				):
 lowerCamelCase_								=  HfArgumentParser((TrainingArguments,)		)
 sys.argv += ["--output_dir", "./examples"]
 lowerCamelCase_								=  parser.parse_args_into_dataclasses()[0]

 logger.warning(
     F'''Process rank: {training_args.local_rank}, device: {training_args.device}, '''
     F'''tpu_num_cores: {training_args.tpu_num_cores}''' ,    )

 # 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 [1001, 256, 15]:
  lowerCamelCase_								=  DummyDataset(UpperCAmelCase_		)

  def compute_metrics(UpperCAmelCase_						:						EvalPrediction		) -> Dict:
   lowerCamelCase_								=  list(range(len(UpperCAmelCase_		)		)		)
   lowerCamelCase_								=  p.predictions.tolist() == sequential and p.label_ids.tolist() == sequential
   return {"success": success}

  lowerCamelCase_								=  Trainer(
      model=DummyModel() ,    args=UpperCAmelCase_ ,    data_collator=DummyDataCollator() ,    eval_dataset=UpperCAmelCase_ ,    compute_metrics=UpperCAmelCase_ ,    )
  lowerCamelCase_								=  trainer.evaluate()
  logger.info(UpperCAmelCase_		)
  if metrics["eval_success"] is not True:
   logger.error(UpperCAmelCase_		)
   exit(1		)

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

  lowerCamelCase_								=  2

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

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

  lowerCamelCase_								=  None

 logger.info("🔥 All distributed tests successful"		)





def __snake_case (				UpperCAmelCase_						:						Optional[int]		):
 # For xla_spawn (TPUs)
 main()


if __name__ == "__main__":
     main()







'''simple docstring'''

def __snake_case (				UpperCAmelCase_						:						float		):
 return -num if num < 0 else num





def __snake_case (				UpperCAmelCase_						:						list[int]		):
 if len(UpperCAmelCase_		) == 0:
  raise ValueError("abs_min() arg is an empty sequence"		)
 lowerCamelCase_								=  x[0]
 for i in x:
  if abs_val(UpperCAmelCase_		) < abs_val(UpperCAmelCase_		):
   lowerCamelCase_								=  i
 return j





def __snake_case (				UpperCAmelCase_						:						list[int]		):
 if len(UpperCAmelCase_		) == 0:
  raise ValueError("abs_max() arg is an empty sequence"		)
 lowerCamelCase_								=  x[0]
 for i in x:
  if abs(UpperCAmelCase_		) > abs(UpperCAmelCase_		):
   lowerCamelCase_								=  i
 return j





def __snake_case (				UpperCAmelCase_						:						list[int]		):
 if len(UpperCAmelCase_		) == 0:
  raise ValueError("abs_max_sort() arg is an empty sequence"		)
 return sorted(UpperCAmelCase_ ,    key=UpperCAmelCase_		)[-1]





def __snake_case (				):
 assert abs_val(0		) == 0
 assert abs_val(34		) == 34
 assert abs_val(-100000000000		) == 100000000000

 lowerCamelCase_								=  [-3, -1, 2, -11]
 assert abs_max(UpperCAmelCase_		) == -11
 assert abs_max_sort(UpperCAmelCase_		) == -11
 assert abs_min(UpperCAmelCase_		) == -1


if __name__ == "__main__":
     import doctest

     doctest.testmod()

     test_abs_val()
     print(abs_val(-34))  # --> 34



