

"""simple docstring"""


import json
import pathlib
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision, slow
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 ConditionalDetrImageProcessor





class        snake_case      (							unittest.TestCase    ):

				def __init__(      self				:							Any	,    UpperCamelCase__				:							List[Any]	,    UpperCamelCase__				:							Dict=7	,    UpperCamelCase__				:							Any=3	,    UpperCamelCase__				:							Union[str, Any]=3_0	,    UpperCamelCase__				:							int=4_0_0	,    UpperCamelCase__				:							Tuple=True	,    UpperCamelCase__				:							Tuple=None	,    UpperCamelCase__				:							int=True	,    UpperCamelCase__				:							str=[0.5, 0.5, 0.5]	,    UpperCamelCase__				:							str=[0.5, 0.5, 0.5]	,    UpperCamelCase__				:							int=True	,    UpperCamelCase__				:							str=1 / 2_5_5	,    UpperCamelCase__				:							Union[str, Any]=True	,    )->  int:



						'''simple docstring'''


						__lowerCAmelCase:			List[Any]        =     size if size is not None else {"shortest_edge": 1_8, "longest_edge": 1_3_3_3}
						__lowerCAmelCase:			Optional[int]        =     parent
						__lowerCAmelCase:			Optional[Any]        =     batch_size
						__lowerCAmelCase:			Optional[Any]        =     num_channels
						__lowerCAmelCase:			List[str]        =     min_resolution
						__lowerCAmelCase:			str        =     max_resolution
						__lowerCAmelCase:			List[Any]        =     do_resize
						__lowerCAmelCase:			Dict        =     size
						__lowerCAmelCase:			Optional[int]        =     do_normalize
						__lowerCAmelCase:			Optional[Any]        =     image_mean
						__lowerCAmelCase:			Any        =     image_std
						__lowerCAmelCase:			List[str]        =     do_rescale
						__lowerCAmelCase:			Any        =     rescale_factor
						__lowerCAmelCase:			Optional[int]        =     do_pad

				def 				lowercase_	(      self				:							Dict)->  Dict:



						'''simple docstring'''


						return {
						    "do_resize": self.do_resize,
						    "size": self.size,
						    "do_normalize": self.do_normalize,
						    "image_mean": self.image_mean,
						    "image_std": self.image_std,
						    "do_rescale": self.do_rescale,
						    "rescale_factor": self.rescale_factor,
						    "do_pad": self.do_pad,
						}




				def 				lowercase_	(      self				:							List[str]	,    UpperCamelCase__				:							Optional[Any]	,    UpperCamelCase__				:							Any=False)->  Union[str, Any]:



						'''simple docstring'''


						if not batched:
								__lowerCAmelCase:			Optional[Any]        =     image_inputs[0]
								if isinstance(_lowerCAmelCase	,    Image.Image):
										__lowerCAmelCase ,					__lowerCAmelCase:			int        =     image.size
								else:
										__lowerCAmelCase ,					__lowerCAmelCase:			Dict        =     image.shape[1], image.shape[2]
								if w < h:
										__lowerCAmelCase:			Any        =     int(self.size["shortest_edge"] * h / w)
										__lowerCAmelCase:			Optional[int]        =     self.size["shortest_edge"]
								elif w > h:
										__lowerCAmelCase:			Optional[int]        =     self.size["shortest_edge"]
										__lowerCAmelCase:			str        =     int(self.size["shortest_edge"] * w / h)
								else:
										__lowerCAmelCase:			Optional[Any]        =     self.size["shortest_edge"]
										__lowerCAmelCase:			List[str]        =     self.size["shortest_edge"]

						else:
								__lowerCAmelCase:			Optional[Any]        =     []
								for image in image_inputs:
										__lowerCAmelCase ,					__lowerCAmelCase:			Union[str, Any]        =     self.get_expected_values([image])
										expected_values.append((expected_height, expected_width))
								__lowerCAmelCase:			Optional[Any]        =     max(_lowerCAmelCase	,    key=lambda UpperCamelCase__: item[0])[0]
								__lowerCAmelCase:			List[str]        =     max(_lowerCAmelCase	,    key=lambda UpperCamelCase__: item[1])[1]

						return expected_height, expected_width





@require_torch
@require_vision
class        snake_case      (							__snake_case,				unittest.TestCase    ):
				SCREAMING_SNAKE_CASE_  : Union[str, Any]   =    ConditionalDetrImageProcessor if is_vision_available() else None

				def 				lowercase_	(      self				:							str)->  List[str]:



						'''simple docstring'''


						__lowerCAmelCase:			Any        =     ConditionalDetrImageProcessingTester(self)

				@property
				def 				lowercase_	(      self				:							Dict)->  str:



						'''simple docstring'''


						return self.image_processor_tester.prepare_image_processor_dict()

				def 				lowercase_	(      self				:							Optional[Any])->  Optional[Any]:



						'''simple docstring'''


						__lowerCAmelCase:			List[Any]        =     self.image_processing_class(**self.image_processor_dict)
						self.assertTrue(hasattr(_lowerCAmelCase	,    "image_mean"))
						self.assertTrue(hasattr(_lowerCAmelCase	,    "image_std"))
						self.assertTrue(hasattr(_lowerCAmelCase	,    "do_normalize"))
						self.assertTrue(hasattr(_lowerCAmelCase	,    "do_resize"))
						self.assertTrue(hasattr(_lowerCAmelCase	,    "size"))

				def 				lowercase_	(      self				:							Optional[Any])->  Dict:



						'''simple docstring'''


						__lowerCAmelCase:			List[Any]        =     self.image_processing_class.from_dict(self.image_processor_dict)
						self.assertEqual(image_processor.size	,    {"shortest_edge": 1_8, "longest_edge": 1_3_3_3})
						self.assertEqual(image_processor.do_pad	,    _lowerCAmelCase)

						__lowerCAmelCase:			Tuple        =     self.image_processing_class.from_dict(
						    self.image_processor_dict	,    size=4_2	,    max_size=8_4	,    pad_and_return_pixel_mask=_lowerCAmelCase)
						self.assertEqual(image_processor.size	,    {"shortest_edge": 4_2, "longest_edge": 8_4})
						self.assertEqual(image_processor.do_pad	,    _lowerCAmelCase)

				def 				lowercase_	(      self				:							Optional[int])->  Tuple:



						'''simple docstring'''


						pass

				def 				lowercase_	(      self				:							Optional[int])->  List[str]:



						'''simple docstring'''


						__lowerCAmelCase:			Tuple        =     self.image_processing_class(**self.image_processor_dict)
						# create random PIL images
						__lowerCAmelCase:			Any        =     prepare_image_inputs(self.image_processor_tester	,    equal_resolution=_lowerCAmelCase)
						for image in image_inputs:
								self.assertIsInstance(_lowerCAmelCase	,    Image.Image)

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

						__lowerCAmelCase ,					__lowerCAmelCase:			List[Any]        =     self.image_processor_tester.get_expected_values(_lowerCAmelCase)

						self.assertEqual(
						    encoded_images.shape	,    (1, self.image_processor_tester.num_channels, expected_height, expected_width)	,    )

						# Test batched
						__lowerCAmelCase ,					__lowerCAmelCase:			int        =     self.image_processor_tester.get_expected_values(_lowerCAmelCase	,    batched=_lowerCAmelCase)

						__lowerCAmelCase:			str        =     image_processing(_lowerCAmelCase	,    return_tensors="pt").pixel_values
						self.assertEqual(
						    encoded_images.shape	,    (
						        self.image_processor_tester.batch_size,
						        self.image_processor_tester.num_channels,
						        expected_height,
						        expected_width,
						    )	,    )

				def 				lowercase_	(      self				:							str)->  Optional[Any]:



						'''simple docstring'''


						__lowerCAmelCase:			List[str]        =     self.image_processing_class(**self.image_processor_dict)
						# create random numpy tensors
						__lowerCAmelCase:			int        =     prepare_image_inputs(self.image_processor_tester	,    equal_resolution=_lowerCAmelCase	,    numpify=_lowerCAmelCase)
						for image in image_inputs:
								self.assertIsInstance(_lowerCAmelCase	,    np.ndarray)

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

						__lowerCAmelCase ,					__lowerCAmelCase:			str        =     self.image_processor_tester.get_expected_values(_lowerCAmelCase)

						self.assertEqual(
						    encoded_images.shape	,    (1, self.image_processor_tester.num_channels, expected_height, expected_width)	,    )

						# Test batched
						__lowerCAmelCase:			Tuple        =     image_processing(_lowerCAmelCase	,    return_tensors="pt").pixel_values

						__lowerCAmelCase ,					__lowerCAmelCase:			int        =     self.image_processor_tester.get_expected_values(_lowerCAmelCase	,    batched=_lowerCAmelCase)

						self.assertEqual(
						    encoded_images.shape	,    (
						        self.image_processor_tester.batch_size,
						        self.image_processor_tester.num_channels,
						        expected_height,
						        expected_width,
						    )	,    )

				def 				lowercase_	(      self				:							Optional[int])->  Optional[Any]:



						'''simple docstring'''


						__lowerCAmelCase:			Tuple        =     self.image_processing_class(**self.image_processor_dict)
						# create random PyTorch tensors
						__lowerCAmelCase:			List[Any]        =     prepare_image_inputs(self.image_processor_tester	,    equal_resolution=_lowerCAmelCase	,    torchify=_lowerCAmelCase)
						for image in image_inputs:
								self.assertIsInstance(_lowerCAmelCase	,    torch.Tensor)

						# Test not batched input
						__lowerCAmelCase:			List[Any]        =     image_processing(image_inputs[0]	,    return_tensors="pt").pixel_values

						__lowerCAmelCase ,					__lowerCAmelCase:			Optional[Any]        =     self.image_processor_tester.get_expected_values(_lowerCAmelCase)

						self.assertEqual(
						    encoded_images.shape	,    (1, self.image_processor_tester.num_channels, expected_height, expected_width)	,    )

						# Test batched
						__lowerCAmelCase:			Dict        =     image_processing(_lowerCAmelCase	,    return_tensors="pt").pixel_values

						__lowerCAmelCase ,					__lowerCAmelCase:			Optional[int]        =     self.image_processor_tester.get_expected_values(_lowerCAmelCase	,    batched=_lowerCAmelCase)

						self.assertEqual(
						    encoded_images.shape	,    (
						        self.image_processor_tester.batch_size,
						        self.image_processor_tester.num_channels,
						        expected_height,
						        expected_width,
						    )	,    )

				@slow
				def 				lowercase_	(      self				:							Optional[Any])->  str:



						'''simple docstring'''


						__lowerCAmelCase:			Tuple        =     Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
						with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt"	,    "r") as f:
								__lowerCAmelCase:			List[Any]        =     json.loads(f.read())

						__lowerCAmelCase:			Union[str, Any]        =     {"image_id": 3_9_7_6_9, "annotations": target}

						# encode them
						__lowerCAmelCase:			List[Any]        =     ConditionalDetrImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50")
						__lowerCAmelCase:			Dict        =     image_processing(images=_lowerCAmelCase	,    annotations=_lowerCAmelCase	,    return_tensors="pt")

						# verify pixel values
						__lowerCAmelCase:			Dict        =     torch.Size([1, 3, 8_0_0, 1_0_6_6])
						self.assertEqual(encoding["pixel_values"].shape	,    _lowerCAmelCase)

						__lowerCAmelCase:			Union[str, Any]        =     torch.tensor([0.2796, 0.3138, 0.3481])
						self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3]	,    _lowerCAmelCase	,    atol=1e-4))

						# verify area
						__lowerCAmelCase:			str        =     torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438])
						self.assertTrue(torch.allclose(encoding["labels"][0]["area"]	,    _lowerCAmelCase))
						# verify boxes
						__lowerCAmelCase:			int        =     torch.Size([6, 4])
						self.assertEqual(encoding["labels"][0]["boxes"].shape	,    _lowerCAmelCase)
						__lowerCAmelCase:			Tuple        =     torch.tensor([0.5503, 0.2765, 0.0604, 0.2215])
						self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0]	,    _lowerCAmelCase	,    atol=1e-3))
						# verify image_id
						__lowerCAmelCase:			int        =     torch.tensor([3_9_7_6_9])
						self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"]	,    _lowerCAmelCase))
						# verify is_crowd
						__lowerCAmelCase:			str        =     torch.tensor([0, 0, 0, 0, 0, 0])
						self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"]	,    _lowerCAmelCase))
						# verify class_labels
						__lowerCAmelCase:			Optional[Any]        =     torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7])
						self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"]	,    _lowerCAmelCase))
						# verify orig_size
						__lowerCAmelCase:			int        =     torch.tensor([4_8_0, 6_4_0])
						self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"]	,    _lowerCAmelCase))
						# verify size
						__lowerCAmelCase:			List[str]        =     torch.tensor([8_0_0, 1_0_6_6])
						self.assertTrue(torch.allclose(encoding["labels"][0]["size"]	,    _lowerCAmelCase))




				@slow
				def 				lowercase_	(      self				:							Tuple)->  List[Any]:



						'''simple docstring'''


						__lowerCAmelCase:			Optional[Any]        =     Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
						with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt"	,    "r") as f:
								__lowerCAmelCase:			Union[str, Any]        =     json.loads(f.read())

						__lowerCAmelCase:			Any        =     {"file_name": "000000039769.png", "image_id": 3_9_7_6_9, "segments_info": target}

						__lowerCAmelCase:			List[str]        =     pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic")

						# encode them
						__lowerCAmelCase:			Union[str, Any]        =     ConditionalDetrImageProcessor(format="coco_panoptic")
						__lowerCAmelCase:			int        =     image_processing(images=_lowerCAmelCase	,    annotations=_lowerCAmelCase	,    masks_path=_lowerCAmelCase	,    return_tensors="pt")

						# verify pixel values
						__lowerCAmelCase:			str        =     torch.Size([1, 3, 8_0_0, 1_0_6_6])
						self.assertEqual(encoding["pixel_values"].shape	,    _lowerCAmelCase)

						__lowerCAmelCase:			str        =     torch.tensor([0.2796, 0.3138, 0.3481])
						self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3]	,    _lowerCAmelCase	,    atol=1e-4))

						# verify area
						__lowerCAmelCase:			Union[str, Any]        =     torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147])
						self.assertTrue(torch.allclose(encoding["labels"][0]["area"]	,    _lowerCAmelCase))
						# verify boxes
						__lowerCAmelCase:			Optional[int]        =     torch.Size([6, 4])
						self.assertEqual(encoding["labels"][0]["boxes"].shape	,    _lowerCAmelCase)
						__lowerCAmelCase:			Dict        =     torch.tensor([0.2625, 0.5437, 0.4688, 0.8625])
						self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0]	,    _lowerCAmelCase	,    atol=1e-3))
						# verify image_id
						__lowerCAmelCase:			List[Any]        =     torch.tensor([3_9_7_6_9])
						self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"]	,    _lowerCAmelCase))
						# verify is_crowd
						__lowerCAmelCase:			Optional[int]        =     torch.tensor([0, 0, 0, 0, 0, 0])
						self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"]	,    _lowerCAmelCase))
						# verify class_labels
						__lowerCAmelCase:			Any        =     torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3])
						self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"]	,    _lowerCAmelCase))
						# verify masks
						__lowerCAmelCase:			Tuple        =     8_2_2_8_7_3
						self.assertEqual(encoding["labels"][0]["masks"].sum().item()	,    _lowerCAmelCase)
						# verify orig_size
						__lowerCAmelCase:			Union[str, Any]        =     torch.tensor([4_8_0, 6_4_0])
						self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"]	,    _lowerCAmelCase))
						# verify size
						__lowerCAmelCase:			Dict        =     torch.tensor([8_0_0, 1_0_6_6])
						self.assertTrue(torch.allclose(encoding["labels"][0]["size"]	,    _lowerCAmelCase))









'''simple docstring'''


import gc
import unittest

import torch
from parameterized import parameterized

from diffusers import AutoencoderKL
from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin


enable_full_determinism()

class  lowerCAmelCase_		(		__magic_name__    ,__magic_name__    ,unittest.TestCase		):
 __lowerCamelCase    :				Optional[Any]								=       AutoencoderKL
 __lowerCamelCase    :				List[Any]								=       "sample"
 __lowerCamelCase    :				Tuple								=       1e-2




 @property
 def 				_snake_case (						self		)     ->				Union[str, Any]:
     _lowerCAmelCase						      =   4
     _lowerCAmelCase						      =   3
     _lowerCAmelCase						      =   (32, 32)

     _lowerCAmelCase						      =   floats_tensor((batch_size, num_channels) + sizes		).to(_lowerCAmelCase		)

     return {"sample": image}




 @property
 def 				_snake_case (						self		)     ->				Any:
     return (3, 32, 32)




 @property
 def 				_snake_case (						self		)     ->				List[Any]:
     return (3, 32, 32)




 def 				_snake_case (						self		)     ->				str:
     _lowerCAmelCase						      =   {
         "block_out_channels": [32, 64],
         "in_channels": 3,
         "out_channels": 3,
         "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"],
         "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"],
         "latent_channels": 4,
     }
     _lowerCAmelCase						      =   self.dummy_input
     return init_dict, inputs_dict




 def 				_snake_case (						self		)     ->				Optional[int]:
     pass




 def 				_snake_case (						self		)     ->				Any:
     pass




 @unittest.skipIf(torch_device == "mps"      ,  "Gradient checkpointing skipped on MPS"		)
 def 				_snake_case (						self		)     ->				str:
     # enable deterministic behavior for gradient checkpointing
     _lowerCAmelCase      ,      _lowerCAmelCase						      =   self.prepare_init_args_and_inputs_for_common()
     _lowerCAmelCase						      =   self.model_class(**_lowerCAmelCase		)
     model.to(_lowerCAmelCase		)

     assert not model.is_gradient_checkpointing and model.training

     _lowerCAmelCase						      =   model(**_lowerCAmelCase		).sample
     # run the backwards pass on the model. For backwards pass, for simplicity purpose,
     # we won't calculate the loss and rather backprop on out.sum()
     model.zero_grad()

     _lowerCAmelCase						      =   torch.randn_like(_lowerCAmelCase		)
     _lowerCAmelCase						      =   (out - labels).mean()
     loss.backward()

     # re-instantiate the model now enabling gradient checkpointing
     _lowerCAmelCase						      =   self.model_class(**_lowerCAmelCase		)
     # clone model
     model_a.load_state_dict(model.state_dict()		)
     model_a.to(_lowerCAmelCase		)
     model_a.enable_gradient_checkpointing()

     assert model_a.is_gradient_checkpointing and model_a.training

     _lowerCAmelCase						      =   model_a(**_lowerCAmelCase		).sample
     # run the backwards pass on the model. For backwards pass, for simplicity purpose,
     # we won't calculate the loss and rather backprop on out.sum()
     model_a.zero_grad()
     _lowerCAmelCase						      =   (out_a - labels).mean()
     loss_a.backward()

     # compare the output and parameters gradients
     self.assertTrue((loss - loss_a).abs() < 1E-5		)
     _lowerCAmelCase						      =   dict(model.named_parameters()		)
     _lowerCAmelCase						      =   dict(model_a.named_parameters()		)
     for name, param in named_params.items():
         self.assertTrue(torch_all_close(param.grad.data      ,  named_params_a[name].grad.data      ,  atol=5E-5		)		)




 def 				_snake_case (						self		)     ->				Optional[Any]:
     _lowerCAmelCase      ,      _lowerCAmelCase						      =   AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy"      ,  output_loading_info=_lowerCAmelCase		)
     self.assertIsNotNone(_lowerCAmelCase		)
     self.assertEqual(len(loading_info["missing_keys"]		)      ,  0		)

     model.to(_lowerCAmelCase		)
     _lowerCAmelCase						      =   model(**self.dummy_input		)

     assert image is not None, "Make sure output is not None"





 def 				_snake_case (						self		)     ->				Dict:
     _lowerCAmelCase						      =   AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy"		)
     _lowerCAmelCase						      =   model.to(_lowerCAmelCase		)
     model.eval()

     if torch_device == "mps":
         _lowerCAmelCase						      =   torch.manual_seed(0		)
     else:
         _lowerCAmelCase						      =   torch.Generator(device=_lowerCAmelCase		).manual_seed(0		)

     _lowerCAmelCase						      =   torch.randn(
         1      ,  model.config.in_channels      ,  model.config.sample_size      ,  model.config.sample_size      ,  generator=torch.manual_seed(0		)      ,  )
     _lowerCAmelCase						      =   image.to(_lowerCAmelCase		)
     with torch.no_grad():
         _lowerCAmelCase						      =   model(_lowerCAmelCase      ,  sample_posterior=_lowerCAmelCase      ,  generator=_lowerCAmelCase		).sample

     _lowerCAmelCase						      =   output[0, -1, -3:, -3:].flatten().cpu()

     # Since the VAE Gaussian prior's generator is seeded on the appropriate device,
     # the expected output slices are not the same for CPU and GPU.
     if torch_device == "mps":
         _lowerCAmelCase						      =   torch.tensor(
             [
                 -4.0078E-01,
                 -3.8323E-04,
                 -1.2681E-01,
                 -1.1462E-01,
                 2.0095E-01,
                 1.0893E-01,
                 -8.8247E-02,
                 -3.0361E-01,
                 -9.8644E-03,
             ]		)
     elif torch_device == "cpu":
         _lowerCAmelCase						      =   torch.tensor(
             [-0.1352, 0.0878, 0.0419, -0.0818, -0.1069, 0.0688, -0.1458, -0.4446, -0.0026]		)
     else:
         _lowerCAmelCase						      =   torch.tensor(
             [-0.2421, 0.4642, 0.2507, -0.0438, 0.0682, 0.3160, -0.2018, -0.0727, 0.2485]		)

     self.assertTrue(torch_all_close(_lowerCAmelCase      ,  _lowerCAmelCase      ,  rtol=1E-2		)		)







@slow
class  lowerCAmelCase_		(		unittest.TestCase		):




 def 				_snake_case (						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase		)     ->				Union[str, Any]:
     return f'''gaussian_noise_s={seed}_shape={'_'.join([str(_lowerCAmelCase		) for s in shape]		)}.npy'''




 def 				_snake_case (						self		)     ->				List[str]:
     # clean up the VRAM after each test
     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()




 def 				_snake_case (						self      ,  _lowerCAmelCase=0      ,  _lowerCAmelCase=(4, 3, 512, 512)      ,  _lowerCAmelCase=False		)     ->				Tuple:
     _lowerCAmelCase						      =   torch.floataa if fpaa else torch.floataa
     _lowerCAmelCase						      =   torch.from_numpy(load_hf_numpy(self.get_file_format(_lowerCAmelCase      ,  _lowerCAmelCase		)		)		).to(_lowerCAmelCase		).to(_lowerCAmelCase		)
     return image




 def 				_snake_case (						self      ,  _lowerCAmelCase="CompVis/stable-diffusion-v1-4"      ,  _lowerCAmelCase=False		)     ->				Tuple:
     _lowerCAmelCase						      =   "fp16" if fpaa else None
     _lowerCAmelCase						      =   torch.floataa if fpaa else torch.floataa

     _lowerCAmelCase						      =   AutoencoderKL.from_pretrained(
         _lowerCAmelCase      ,  subfolder="vae"      ,  torch_dtype=_lowerCAmelCase      ,  revision=_lowerCAmelCase      ,  )
     model.to(_lowerCAmelCase		).eval()

     return model




 def 				_snake_case (						self      ,  _lowerCAmelCase=0		)     ->				str:
     if torch_device == "mps":
         return torch.manual_seed(_lowerCAmelCase		)
     return torch.Generator(device=_lowerCAmelCase		).manual_seed(_lowerCAmelCase		)




 @parameterized.expand(
     [
         # fmt: off
         [33, [-0.1603, 0.9878, -0.0495, -0.0790, -0.2709, 0.8375, -0.2060, -0.0824], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]],
         [47, [-0.2376, 0.1168, 0.1332, -0.4840, -0.2508, -0.0791, -0.0493, -0.4089], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]],
         # fmt: on
     ]		)
 def 				_snake_case (						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase		)     ->				Dict:
     _lowerCAmelCase						      =   self.get_sd_vae_model()
     _lowerCAmelCase						      =   self.get_sd_image(_lowerCAmelCase		)
     _lowerCAmelCase						      =   self.get_generator(_lowerCAmelCase		)

     with torch.no_grad():
         _lowerCAmelCase						      =   model(_lowerCAmelCase      ,  generator=_lowerCAmelCase      ,  sample_posterior=_lowerCAmelCase		).sample

     assert sample.shape == image.shape

     _lowerCAmelCase						      =   sample[-1, -2:, -2:, :2].flatten().float().cpu()
     _lowerCAmelCase						      =   torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice		)

     assert torch_all_close(_lowerCAmelCase      ,  _lowerCAmelCase      ,  atol=3E-3		)




 @parameterized.expand(
     [
         # fmt: off
         [33, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]],
         [47, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]],
         # fmt: on
     ]		)
 @require_torch_gpu
 def 				_snake_case (						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase		)     ->				Optional[Any]:
     _lowerCAmelCase						      =   self.get_sd_vae_model(fpaa=_lowerCAmelCase		)
     _lowerCAmelCase						      =   self.get_sd_image(_lowerCAmelCase      ,  fpaa=_lowerCAmelCase		)
     _lowerCAmelCase						      =   self.get_generator(_lowerCAmelCase		)

     with torch.no_grad():
         _lowerCAmelCase						      =   model(_lowerCAmelCase      ,  generator=_lowerCAmelCase      ,  sample_posterior=_lowerCAmelCase		).sample

     assert sample.shape == image.shape

     _lowerCAmelCase						      =   sample[-1, -2:, :2, -2:].flatten().float().cpu()
     _lowerCAmelCase						      =   torch.tensor(_lowerCAmelCase		)

     assert torch_all_close(_lowerCAmelCase      ,  _lowerCAmelCase      ,  atol=1E-2		)




 @parameterized.expand(
     [
         # fmt: off
         [33, [-0.1609, 0.9866, -0.0487, -0.0777, -0.2716, 0.8368, -0.2055, -0.0814], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]],
         [47, [-0.2377, 0.1147, 0.1333, -0.4841, -0.2506, -0.0805, -0.0491, -0.4085], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]],
         # fmt: on
     ]		)
 def 				_snake_case (						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase		)     ->				Tuple:
     _lowerCAmelCase						      =   self.get_sd_vae_model()
     _lowerCAmelCase						      =   self.get_sd_image(_lowerCAmelCase		)

     with torch.no_grad():
         _lowerCAmelCase						      =   model(_lowerCAmelCase		).sample

     assert sample.shape == image.shape

     _lowerCAmelCase						      =   sample[-1, -2:, -2:, :2].flatten().float().cpu()
     _lowerCAmelCase						      =   torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice		)

     assert torch_all_close(_lowerCAmelCase      ,  _lowerCAmelCase      ,  atol=3E-3		)




 @parameterized.expand(
     [
         # fmt: off
         [13, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]],
         [37, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]],
         # fmt: on
     ]		)
 @require_torch_gpu
 def 				_snake_case (						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase		)     ->				Optional[Any]:
     _lowerCAmelCase						      =   self.get_sd_vae_model()
     _lowerCAmelCase						      =   self.get_sd_image(_lowerCAmelCase      ,  shape=(3, 4, 64, 64)		)

     with torch.no_grad():
         _lowerCAmelCase						      =   model.decode(_lowerCAmelCase		).sample

     assert list(sample.shape		) == [3, 3, 512, 512]

     _lowerCAmelCase						      =   sample[-1, -2:, :2, -2:].flatten().cpu()
     _lowerCAmelCase						      =   torch.tensor(_lowerCAmelCase		)

     assert torch_all_close(_lowerCAmelCase      ,  _lowerCAmelCase      ,  atol=1E-3		)




 @parameterized.expand(
     [
         # fmt: off
         [27, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]],
         [16, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]],
         # fmt: on
     ]		)
 @require_torch_gpu
 def 				_snake_case (						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase		)     ->				str:
     _lowerCAmelCase						      =   self.get_sd_vae_model(fpaa=_lowerCAmelCase		)
     _lowerCAmelCase						      =   self.get_sd_image(_lowerCAmelCase      ,  shape=(3, 4, 64, 64)      ,  fpaa=_lowerCAmelCase		)

     with torch.no_grad():
         _lowerCAmelCase						      =   model.decode(_lowerCAmelCase		).sample

     assert list(sample.shape		) == [3, 3, 512, 512]

     _lowerCAmelCase						      =   sample[-1, -2:, :2, -2:].flatten().float().cpu()
     _lowerCAmelCase						      =   torch.tensor(_lowerCAmelCase		)

     assert torch_all_close(_lowerCAmelCase      ,  _lowerCAmelCase      ,  atol=5E-3		)




 @parameterized.expand([(13,), (16,), (27,)]		)
 @require_torch_gpu
 @unittest.skipIf(not is_xformers_available()      ,  reason="xformers is not required when using PyTorch 2.0."		)
 def 				_snake_case (						self      ,  _lowerCAmelCase		)     ->				List[str]:
     _lowerCAmelCase						      =   self.get_sd_vae_model(fpaa=_lowerCAmelCase		)
     _lowerCAmelCase						      =   self.get_sd_image(_lowerCAmelCase      ,  shape=(3, 4, 64, 64)      ,  fpaa=_lowerCAmelCase		)

     with torch.no_grad():
         _lowerCAmelCase						      =   model.decode(_lowerCAmelCase		).sample

     model.enable_xformers_memory_efficient_attention()
     with torch.no_grad():
         _lowerCAmelCase						      =   model.decode(_lowerCAmelCase		).sample

     assert list(sample.shape		) == [3, 3, 512, 512]

     assert torch_all_close(_lowerCAmelCase      ,  _lowerCAmelCase      ,  atol=1E-1		)




 @parameterized.expand([(13,), (16,), (37,)]		)
 @require_torch_gpu
 @unittest.skipIf(not is_xformers_available()      ,  reason="xformers is not required when using PyTorch 2.0."		)
 def 				_snake_case (						self      ,  _lowerCAmelCase		)     ->				Any:
     _lowerCAmelCase						      =   self.get_sd_vae_model()
     _lowerCAmelCase						      =   self.get_sd_image(_lowerCAmelCase      ,  shape=(3, 4, 64, 64)		)

     with torch.no_grad():
         _lowerCAmelCase						      =   model.decode(_lowerCAmelCase		).sample

     model.enable_xformers_memory_efficient_attention()
     with torch.no_grad():
         _lowerCAmelCase						      =   model.decode(_lowerCAmelCase		).sample

     assert list(sample.shape		) == [3, 3, 512, 512]

     assert torch_all_close(_lowerCAmelCase      ,  _lowerCAmelCase      ,  atol=1E-2		)





 @parameterized.expand(
     [
         # fmt: off
         [33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]],
         [47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]],
         # fmt: on
     ]		)
 def 				_snake_case (						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase		)     ->				int:
     _lowerCAmelCase						      =   self.get_sd_vae_model()
     _lowerCAmelCase						      =   self.get_sd_image(_lowerCAmelCase		)
     _lowerCAmelCase						      =   self.get_generator(_lowerCAmelCase		)

     with torch.no_grad():
         _lowerCAmelCase						      =   model.encode(_lowerCAmelCase		).latent_dist
         _lowerCAmelCase						      =   dist.sample(generator=_lowerCAmelCase		)

     assert list(sample.shape		) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]]

     _lowerCAmelCase						      =   sample[0, -1, -3:, -3:].flatten().cpu()
     _lowerCAmelCase						      =   torch.tensor(_lowerCAmelCase		)

     _lowerCAmelCase						      =   3E-3 if torch_device != "mps" else 1E-2
     assert torch_all_close(_lowerCAmelCase      ,  _lowerCAmelCase      ,  atol=_lowerCAmelCase		)


