






"""simple docstring"""


import random
import unittest

import numpy as np
import torch

from diffusers import DDIMScheduler, LDMSuperResolutionPipeline, UNetaDModel, VQModel
from diffusers.utils import PIL_INTERPOLATION, floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch


enable_full_determinism()


class  snake_case		(							unittest.TestCase						):


   '''simple docstring'''

   @property
   def     _SCREAMING_SNAKE_CASE    (     self			:					int  ):

     '''simple docstring'''
     __A						      =			1
     __A						      =			3
     __A						      =			(32, 32)

     __A						      =			floats_tensor((batch_size, num_channels) + sizes,	rng=random.Random(0  )  ).to(_lowerCamelCase  )
     return image


   @property
   def     _SCREAMING_SNAKE_CASE    (     self			:					List[Any]  ):

     '''simple docstring'''
     torch.manual_seed(0  )
     __A						      =			UNetaDModel(
         block_out_channels=(32, 64),	layers_per_block=2,	sample_size=32,	in_channels=6,	out_channels=3,	down_block_types=('''DownBlock2D''', '''AttnDownBlock2D'''),	up_block_types=('''AttnUpBlock2D''', '''UpBlock2D'''),	)
     return model


   @property
   def     _SCREAMING_SNAKE_CASE    (     self			:					List[str]  ):

     '''simple docstring'''
     torch.manual_seed(0  )
     __A						      =			VQModel(
         block_out_channels=[32, 64],	in_channels=3,	out_channels=3,	down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''],	up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''],	latent_channels=3,	)
     return model


   def     _SCREAMING_SNAKE_CASE    (     self			:					Optional[Any]  ):

     '''simple docstring'''
     __A						      =			'''cpu'''
     __A						      =			self.dummy_uncond_unet
     __A						      =			DDIMScheduler()
     __A						      =			self.dummy_vq_model

     __A						      =			LDMSuperResolutionPipeline(unet=_lowerCamelCase,	vqvae=_lowerCamelCase,	scheduler=_lowerCamelCase  )
     ldm.to(_lowerCamelCase  )
     ldm.set_progress_bar_config(disable=_lowerCamelCase  )

     __A						      =			self.dummy_image.to(_lowerCamelCase  )

     __A						      =			torch.Generator(device=_lowerCamelCase  ).manual_seed(0  )
     __A						      =			ldm(image=_lowerCamelCase,	generator=_lowerCamelCase,	num_inference_steps=2,	output_type='''numpy'''  ).images

     __A						      =			image[0, -3:, -3:, -1]

     assert image.shape == (1, 64, 64, 3)
     __A						      =			np.array([0.86_78, 0.82_45, 0.63_81, 0.68_30, 0.43_85, 0.55_99, 0.46_41, 0.62_01, 0.51_50]  )

     assert np.abs(image_slice.flatten() - expected_slice  ).max() < 1e-2






   @unittest.skipIf(torch_device != '''cuda''',	'''This test requires a GPU'''  )
   def     _SCREAMING_SNAKE_CASE    (     self			:					Union[str, Any]  ):

     '''simple docstring'''
     __A						      =			self.dummy_uncond_unet
     __A						      =			DDIMScheduler()
     __A						      =			self.dummy_vq_model

     # put models in fp16
     __A						      =			unet.half()
     __A						      =			vqvae.half()

     __A						      =			LDMSuperResolutionPipeline(unet=_lowerCamelCase,	vqvae=_lowerCamelCase,	scheduler=_lowerCamelCase  )
     ldm.to(_lowerCamelCase  )
     ldm.set_progress_bar_config(disable=_lowerCamelCase  )

     __A						      =			self.dummy_image.to(_lowerCamelCase  )

     __A						      =			ldm(_lowerCamelCase,	num_inference_steps=2,	output_type='''numpy'''  ).images

     assert image.shape == (1, 64, 64, 3)





@slow
@require_torch
class  snake_case		(							unittest.TestCase						):


   '''simple docstring'''

   def     _SCREAMING_SNAKE_CASE    (     self			:					Union[str, Any]  ):

     '''simple docstring'''
     __A						      =			load_image(
         '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
         '''/vq_diffusion/teddy_bear_pool.png'''  )
     __A						      =			init_image.resize((64, 64),	resample=PIL_INTERPOLATION['''lanczos''']  )

     __A						      =			LDMSuperResolutionPipeline.from_pretrained('''duongna/ldm-super-resolution''',	device_map='''auto'''  )
     ldm.set_progress_bar_config(disable=_lowerCamelCase  )

     __A						      =			torch.manual_seed(0  )
     __A						      =			ldm(image=_lowerCamelCase,	generator=_lowerCamelCase,	num_inference_steps=20,	output_type='''numpy'''  ).images

     __A						      =			image[0, -3:, -3:, -1]

     assert image.shape == (1, 2_56, 2_56, 3)
     __A						      =			np.array([0.76_44, 0.76_79, 0.76_42, 0.76_33, 0.76_66, 0.75_60, 0.74_25, 0.72_57, 0.69_07]  )

     assert np.abs(image_slice.flatten() - expected_slice  ).max() < 1e-2












"""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  snake_case		(							_lowerCAmelCase						):


          '''simple docstring'''

          def __init__(     self			:					List[Any],	_lowerCamelCase			:					int = 1_01  ):

            '''simple docstring'''
            __A						      =			length


          def __len__(     self			:					Optional[int]  ):

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






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

            '''simple docstring'''
            return i





       class  snake_case		:


          '''simple docstring'''

          def __call__(     self			:					Tuple,	_lowerCamelCase			:					Dict  ):

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





       class  snake_case		(							nn.Module						):


          '''simple docstring'''

          def __init__(     self			:					List[str]  ):

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






          def     _SCREAMING_SNAKE_CASE    (     self			:					Optional[Any],	_lowerCamelCase			:					Tuple,	_lowerCamelCase			:					Optional[Any]=None  ):

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



def  lowerCAmelCase    (   ):




  """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 [1_0_0_1, 2_5_6, 1_5]:
    __A						      =			DummyDataset(__UpperCamelCase			)

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

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

    __A						      =			trainer.predict(__UpperCamelCase			)
    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(__UpperCamelCase			)
    if metrics["eval_success"] is not True:
      logger.error(__UpperCamelCase			)
      exit(1			)

    __A						      =			trainer.predict(__UpperCamelCase			)
    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  lowerCAmelCase    (   __UpperCamelCase			):




  """simple docstring"""







  main()


if __name__ == "__main__":
       main()




