'''simple docstring'''





import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image

    from transformers import PoolFormerImageProcessor




class 	__A				(			unittest.TestCase     ):



    def __init__(self   :   int       ,      __a   :   str       ,      __a   :   int=7       ,      __a   :   str=3       ,      __a   :   str=30       ,      __a   :   List[str]=400       ,      __a   :   Union[str, Any]=True       ,      __a   :   Optional[Any]=None       ,      __a   :   Union[str, Any]=0.9       ,      __a   :   Any=None       ,      __a   :   List[str]=True       ,      __a   :   Optional[Any]=[0.5, 0.5, 0.5]       ,      __a   :   Dict=[0.5, 0.5, 0.5]       ,      ):
         UpperCAmelCase_	   =       size if size is not None else {"shortest_edge": 30}
         UpperCAmelCase_	   =       crop_size if crop_size is not None else {"height": 30, "width": 30}
         UpperCAmelCase_	   =       parent
         UpperCAmelCase_	   =       batch_size
         UpperCAmelCase_	   =       num_channels
         UpperCAmelCase_	   =       min_resolution
         UpperCAmelCase_	   =       max_resolution
         UpperCAmelCase_	   =       do_resize_and_center_crop
         UpperCAmelCase_	   =       size
         UpperCAmelCase_	   =       crop_pct
         UpperCAmelCase_	   =       crop_size
         UpperCAmelCase_	   =       do_normalize
         UpperCAmelCase_	   =       image_mean
         UpperCAmelCase_	   =       image_std






    def  _lowercase						(self   :   Optional[Any]			):
         return {
             "size": self.size,
             "do_resize_and_center_crop": self.do_resize_and_center_crop,
             "crop_pct": self.crop_pct,
             "crop_size": self.crop_size,
             "do_normalize": self.do_normalize,
             "image_mean": self.image_mean,
             "image_std": self.image_std,
         }




@require_torch
@require_vision
class 	__A				(			UpperCamelCase__		,     unittest.TestCase     ):
    a__	:						Any	       =  PoolFormerImageProcessor if is_vision_available() else None



    def  _lowercase						(self   :   Optional[int]			):
         UpperCAmelCase_	   =       PoolFormerImageProcessingTester(self			)



    @property
    def  _lowercase						(self   :   List[Any]			):
         return self.image_processor_tester.prepare_image_processor_dict()



    def  _lowercase						(self   :   Dict			):
         UpperCAmelCase_	   =       self.image_processing_class(**self.image_processor_dict			)
         self.assertTrue(hasattr(__a       ,      "do_resize_and_center_crop"			)			)
         self.assertTrue(hasattr(__a       ,      "size"			)			)
         self.assertTrue(hasattr(__a       ,      "crop_pct"			)			)
         self.assertTrue(hasattr(__a       ,      "do_normalize"			)			)
         self.assertTrue(hasattr(__a       ,      "image_mean"			)			)
         self.assertTrue(hasattr(__a       ,      "image_std"			)			)



    def  _lowercase						(self   :   Union[str, Any]			):
         UpperCAmelCase_	   =       self.image_processing_class.from_dict(self.image_processor_dict			)
         self.assertEqual(image_processor.size       ,      {"shortest_edge": 30}			)
         self.assertEqual(image_processor.crop_size       ,      {"height": 30, "width": 30}			)

         UpperCAmelCase_	   =       self.image_processing_class.from_dict(self.image_processor_dict       ,      size=42       ,      crop_size=84			)
         self.assertEqual(image_processor.size       ,      {"shortest_edge": 42}			)
         self.assertEqual(image_processor.crop_size       ,      {"height": 84, "width": 84}			)



    def  _lowercase						(self   :   Optional[Any]			):
         pass



    def  _lowercase						(self   :   int			):
         # Initialize image_processing
         UpperCAmelCase_	   =       self.image_processing_class(**self.image_processor_dict			)
         # create random PIL images
         UpperCAmelCase_	   =       prepare_image_inputs(self.image_processor_tester       ,      equal_resolution=__a			)
         for image in image_inputs:
              self.assertIsInstance(__a       ,      Image.Image			)

         # Test not batched input
         UpperCAmelCase_	   =       image_processing(image_inputs[0]       ,      return_tensors="pt"			).pixel_values

         self.assertEqual(
             encoded_images.shape       ,      (
                 1,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.crop_size["height"],
                 self.image_processor_tester.crop_size["width"],
             )       ,      )

         # Test batched
         UpperCAmelCase_	   =       image_processing(__a       ,      return_tensors="pt"			).pixel_values
         self.assertEqual(
             encoded_images.shape       ,      (
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.crop_size["height"],
                 self.image_processor_tester.crop_size["width"],
             )       ,      )



    def  _lowercase						(self   :   Dict			):
         # Initialize image_processing
         UpperCAmelCase_	   =       self.image_processing_class(**self.image_processor_dict			)
         # create random numpy tensors
         UpperCAmelCase_	   =       prepare_image_inputs(self.image_processor_tester       ,      equal_resolution=__a       ,      numpify=__a			)
         for image in image_inputs:
              self.assertIsInstance(__a       ,      np.ndarray			)

         # Test not batched input
         UpperCAmelCase_	   =       image_processing(image_inputs[0]       ,      return_tensors="pt"			).pixel_values
         self.assertEqual(
             encoded_images.shape       ,      (
                 1,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.crop_size["height"],
                 self.image_processor_tester.crop_size["width"],
             )       ,      )

         # Test batched
         UpperCAmelCase_	   =       image_processing(__a       ,      return_tensors="pt"			).pixel_values
         self.assertEqual(
             encoded_images.shape       ,      (
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.crop_size["height"],
                 self.image_processor_tester.crop_size["width"],
             )       ,      )






    def  _lowercase						(self   :   List[Any]			):
         # Initialize image_processing
         UpperCAmelCase_	   =       self.image_processing_class(**self.image_processor_dict			)
         # create random PyTorch tensors
         UpperCAmelCase_	   =       prepare_image_inputs(self.image_processor_tester       ,      equal_resolution=__a       ,      torchify=__a			)
         for image in image_inputs:
              self.assertIsInstance(__a       ,      torch.Tensor			)

         # Test not batched input
         UpperCAmelCase_	   =       image_processing(image_inputs[0]       ,      return_tensors="pt"			).pixel_values
         self.assertEqual(
             encoded_images.shape       ,      (
                 1,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.crop_size["height"],
                 self.image_processor_tester.crop_size["width"],
             )       ,      )

         # Test batched
         UpperCAmelCase_	   =       image_processing(__a       ,      return_tensors="pt"			).pixel_values
         self.assertEqual(
             encoded_images.shape       ,      (
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.crop_size["height"],
                 self.image_processor_tester.crop_size["width"],
             )       ,      )





'''simple docstring'''





import unittest
from typing import Tuple

import torch

from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device
from diffusers.utils.testing_utils import require_torch




@require_torch
class 	__A				:



    @property
    def  _lowercase						(self   :   int			):
         return self.get_dummy_input()



    @property
    def  _lowercase						(self   :   Any			):
         if self.block_type == "down":
              return (4, 32, 16, 16)
         elif self.block_type == "mid":
              return (4, 32, 32, 32)
         elif self.block_type == "up":
              return (4, 32, 64, 64)

         raise ValueError(f"""'{self.block_type}' is not a supported block_type. Set it to 'up', 'mid', or 'down'."""			)



    def  _lowercase						(self   :   Tuple       ,      __a   :   List[str]=True       ,      __a   :   Any=False       ,      __a   :   List[Any]=False       ,      __a   :   Any=False       ,      ):
         UpperCAmelCase_	   =       4
         UpperCAmelCase_	   =       32
         UpperCAmelCase_	   =       (32, 32)

         UpperCAmelCase_	   =       torch.manual_seed(0			)
         UpperCAmelCase_	   =       torch.device(__a			)
         UpperCAmelCase_	   =       (batch_size, num_channels) + sizes
         UpperCAmelCase_	   =       randn_tensor(__a       ,      generator=__a       ,      device=__a			)
         UpperCAmelCase_	   =       {"hidden_states": hidden_states}

         if include_temb:
              UpperCAmelCase_	   =       128
              UpperCAmelCase_	   =       randn_tensor((batch_size, temb_channels)       ,      generator=__a       ,      device=__a			)

         if include_res_hidden_states_tuple:
              UpperCAmelCase_	   =       torch.manual_seed(1			)
              UpperCAmelCase_	   =       (randn_tensor(__a       ,      generator=__a       ,      device=__a			),)

         if include_encoder_hidden_states:
              UpperCAmelCase_	   =       floats_tensor((batch_size, 32, 32)			).to(__a			)

         if include_skip_sample:
              UpperCAmelCase_	   =       randn_tensor(((batch_size, 3) + sizes)       ,      generator=__a       ,      device=__a			)

         return dummy_input



    def  _lowercase						(self   :   Tuple			):
         UpperCAmelCase_	   =       {
             "in_channels": 32,
             "out_channels": 32,
             "temb_channels": 128,
         }
         if self.block_type == "up":
              UpperCAmelCase_	   =       32

         if self.block_type == "mid":
              init_dict.pop("out_channels"			)

         UpperCAmelCase_	   =       self.dummy_input
         return init_dict, inputs_dict



    def  _lowercase						(self   :   Tuple       ,      __a   :   Any			):
         UpperCAmelCase_   ,			UpperCAmelCase_	   =       self.prepare_init_args_and_inputs_for_common()
         UpperCAmelCase_	   =       self.block_class(**__a			)
         unet_block.to(__a			)
         unet_block.eval()

         with torch.no_grad():
              UpperCAmelCase_	   =       unet_block(**__a			)

         if isinstance(__a       ,      __a			):
              UpperCAmelCase_	   =       output[0]

         self.assertEqual(output.shape       ,      self.output_shape			)

         UpperCAmelCase_	   =       output[0, -1, -3:, -3:]
         UpperCAmelCase_	   =       torch.tensor(__a			).to(__a			)
         assert torch_all_close(output_slice.flatten()       ,      __a       ,      atol=5E-3			)






    @unittest.skipIf(torch_device == "mps"       ,      "Training is not supported in mps"			)
    def  _lowercase						(self   :   Dict			):
         UpperCAmelCase_   ,			UpperCAmelCase_	   =       self.prepare_init_args_and_inputs_for_common()
         UpperCAmelCase_	   =       self.block_class(**__a			)
         model.to(__a			)
         model.train()
         UpperCAmelCase_	   =       model(**__a			)

         if isinstance(__a       ,      __a			):
              UpperCAmelCase_	   =       output[0]

         UpperCAmelCase_	   =       torch.device(__a			)
         UpperCAmelCase_	   =       randn_tensor(output.shape       ,      device=__a			)
         UpperCAmelCase_	   =       torch.nn.functional.mse_loss(__a       ,      __a			)
         loss.backward()




