


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


lowercase__					  =		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     __SCREAMING_SNAKE_CASE       (   lowerCamelCase__			):






        def __init__(      self  ,				__UpperCamelCase = 101		)							->     Dict:
             _a            =		length






        def __len__(      self		)							->     int:
             return self.length






        def __getitem__(      self  ,				__UpperCamelCase		)							->     int:
             return i







   class     __SCREAMING_SNAKE_CASE       :






        def __call__(      self  ,				__UpperCamelCase		)							->     Tuple:
             return {"input_ids": torch.tensor(__UpperCamelCase		), "labels": torch.tensor(__UpperCamelCase		)}







   class     __SCREAMING_SNAKE_CASE       (   nn.Module			):






        def __init__(      self		)							->     List[Any]:
             super().__init__()
             # Add some (unused) params otherwise DDP will complain.
             _a            =		nn.Linear(120  ,				80		)






        def 			a_       (      self  ,				__UpperCamelCase  ,				__UpperCamelCase=None		)							->     Optional[Any]:
             if labels is not None:
                  return torch.tensor(0.0  ,				device=input_ids.device		), input_ids
             else:
                  return input_ids






def __UpperCamelCase (      )   ->  Optional[int]:







     '''simple docstring'''






     _a            =		HfArgumentParser((TrainingArguments,)					)
     sys.argv += ["--output_dir", "./examples"]
     _a            =		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]:
          _a            =		DummyDataset(__lowerCamelCase					)

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

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

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

          _a            =		2

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

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

          _a            =		None

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






def __UpperCamelCase (      __lowerCamelCase		:			List[Any]					)   ->  int:







     '''simple docstring'''






     main()


if __name__ == "__main__":
   main()





'''simple docstring'''

import random
import unittest

import torch

from diffusers import IFImgaImgPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin





@skip_mps
class     __SCREAMING_SNAKE_CASE       (   lowerCamelCase__			,      lowerCamelCase__			,      unittest.TestCase			):
     UpperCAmelCase			       =					IFImgaImgPipeline
     UpperCAmelCase			       =					TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''width''', '''height'''}
     UpperCAmelCase			       =					TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
     UpperCAmelCase			       =					PipelineTesterMixin.required_optional_params - {'''latents'''}






     def 			a_       (      self		)							->     Optional[Any]:
          return self._get_dummy_components()






     def 			a_       (      self  ,				__UpperCamelCase  ,				__UpperCamelCase=0		)							->     Any:
          if str(__UpperCamelCase		).startswith("mps"		):
               _a            =		torch.manual_seed(__UpperCamelCase		)
          else:
               _a            =		torch.Generator(device=__UpperCamelCase		).manual_seed(__UpperCamelCase		)

          _a            =		floats_tensor((1, 3, 32, 32)  ,				rng=random.Random(__UpperCamelCase		)		).to(__UpperCamelCase		)

          _a            =		{
              "prompt": "A painting of a squirrel eating a burger",
              "image": image,
              "generator": generator,
              "num_inference_steps": 2,
              "output_type": "numpy",
          }

          return inputs






     def 			a_       (      self		)							->     Any:
          self._test_save_load_optional_components()






     @unittest.skipIf(
         torch_device != "cuda" or not is_xformers_available()  ,				reason="XFormers attention is only available with CUDA and `xformers` installed"  ,				)
     def 			a_       (      self		)							->     Dict:
          self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3		)






     @unittest.skipIf(torch_device != "cuda"  ,				reason="float16 requires CUDA"		)
     def 			a_       (      self		)							->     List[Any]:
          # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
          super().test_save_load_floataa(expected_max_diff=1e-1		)






     @unittest.skipIf(torch_device != "cuda"  ,				reason="float16 requires CUDA"		)
     def 			a_       (      self		)							->     int:
          super().test_floataa_inference(expected_max_diff=1e-1		)






     def 			a_       (      self		)							->     Dict:
          self._test_attention_slicing_forward_pass(expected_max_diff=1e-2		)






     def 			a_       (      self		)							->     Optional[Any]:
          self._test_save_load_local()






     def 			a_       (      self		)							->     Union[str, Any]:
          self._test_inference_batch_single_identical(
              expected_max_diff=1e-2  ,				)

