# 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


__lowerCamelCase     :					List[str]				  =						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							(		lowerCamelCase_						):




      def __init__(       self     :							Tuple			,      _lowercase     :							int = 1_01 ):



        """simple docstring"""






        SCREAMING_SNAKE_CASE__     				= length




      def __len__(       self     :							str ):



        """simple docstring"""






        return self.length




      def __getitem__(       self     :							Optional[Any]			,      _lowercase     :							Union[str, Any] ):



        """simple docstring"""






        return i







   class __snake_case							:




      def __call__(       self     :							Dict			,      _lowercase     :							Dict ):



        """simple docstring"""






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







   class __snake_case							(		nn.Module						):




      def __init__(       self     :							Tuple ):



        """simple docstring"""






        super().__init__()
        # Add some (unused) params otherwise DDP will complain.
        SCREAMING_SNAKE_CASE__     				= nn.Linear(1_20			,      80 )




      def       __a		(       self     :							Any			,      _lowercase     :							Union[str, Any]			,      _lowercase     :							Dict=None ):



        """simple docstring"""






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



def       __SCREAMING_SNAKE_CASE    (   )				->   Optional[Any]:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__     				= HfArgumentParser((TrainingArguments,)      )
  sys.argv += ["--output_dir", "./examples"]
  SCREAMING_SNAKE_CASE__     				= 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 [10_01, 2_56, 15]:
    SCREAMING_SNAKE_CASE__     				= DummyDataset(__UpperCamelCase      )

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

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

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

    SCREAMING_SNAKE_CASE__     				= 2

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

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

    SCREAMING_SNAKE_CASE__     				= None

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



def       __SCREAMING_SNAKE_CASE    (   __UpperCamelCase       :			Union[str, Any]      )				->   Dict:







  """simple docstring"""





  main()


if __name__ == "__main__":
   main()

from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


__lowerCamelCase     :					Optional[int]				  =						{'''configuration_vilt''': ['''VILT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ViltConfig''']}

try:
   if not is_vision_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   __lowerCamelCase     :					Dict				  =						['''ViltFeatureExtractor''']
   __lowerCamelCase     :					Dict				  =						['''ViltImageProcessor''']
   __lowerCamelCase     :					str				  =						['''ViltProcessor''']

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   __lowerCamelCase     :					Any				  =						[
       '''VILT_PRETRAINED_MODEL_ARCHIVE_LIST''',
       '''ViltForImageAndTextRetrieval''',
       '''ViltForImagesAndTextClassification''',
       '''ViltForTokenClassification''',
       '''ViltForMaskedLM''',
       '''ViltForQuestionAnswering''',
       '''ViltLayer''',
       '''ViltModel''',
       '''ViltPreTrainedModel''',
   ]


if TYPE_CHECKING:
   from .configuration_vilt import VILT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViltConfig

   try:
      if not is_vision_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .feature_extraction_vilt import ViltFeatureExtractor
      from .image_processing_vilt import ViltImageProcessor
      from .processing_vilt import ViltProcessor

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_vilt import (
          VILT_PRETRAINED_MODEL_ARCHIVE_LIST,
          ViltForImageAndTextRetrieval,
          ViltForImagesAndTextClassification,
          ViltForMaskedLM,
          ViltForQuestionAnswering,
          ViltForTokenClassification,
          ViltLayer,
          ViltModel,
          ViltPreTrainedModel,
      )


else:
   import sys

   __lowerCamelCase     :					List[str]				  =						_LazyModule(__name__, globals()['''__file__'''], _import_structure)
