




import collections
import inspect
import unittest

from transformers import DonutSwinConfig
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import is_torch_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch
    from torch import nn

    from transformers import DonutSwinModel
    from transformers.models.donut.modeling_donut_swin import DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST
class       __a					:


     """simple docstring"""


     def __init__(	self			: Dict				,_UpperCamelCase			: str				,_UpperCamelCase			: Any=1_3				,_UpperCamelCase			: str=3_2				,_UpperCamelCase			: Optional[Any]=2				,_UpperCamelCase			: List[str]=3				,_UpperCamelCase			: Any=1_6				,_UpperCamelCase			: Any=[1, 2, 1]				,_UpperCamelCase			: Dict=[2, 2, 4]				,_UpperCamelCase			: str=2				,_UpperCamelCase			: int=2.0				,_UpperCamelCase			: Optional[int]=True				,_UpperCamelCase			: int=0.0				,_UpperCamelCase			: Any=0.0				,_UpperCamelCase			: Union[str, Any]=0.1				,_UpperCamelCase			: List[Any]="gelu"				,_UpperCamelCase			: Tuple=False				,_UpperCamelCase			: List[str]=True				,_UpperCamelCase			: List[Any]=0.02				,_UpperCamelCase			: Dict=1e-5				,_UpperCamelCase			: str=True				,_UpperCamelCase			: int=None				,_UpperCamelCase			: List[Any]=True				,_UpperCamelCase			: Tuple=1_0				,_UpperCamelCase			: Tuple=8				,)		->   Any:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=parent
         SCREAMING_SNAKE_CASE__								=batch_size
         SCREAMING_SNAKE_CASE__								=image_size
         SCREAMING_SNAKE_CASE__								=patch_size
         SCREAMING_SNAKE_CASE__								=num_channels
         SCREAMING_SNAKE_CASE__								=embed_dim
         SCREAMING_SNAKE_CASE__								=depths
         SCREAMING_SNAKE_CASE__								=num_heads
         SCREAMING_SNAKE_CASE__								=window_size
         SCREAMING_SNAKE_CASE__								=mlp_ratio
         SCREAMING_SNAKE_CASE__								=qkv_bias
         SCREAMING_SNAKE_CASE__								=hidden_dropout_prob
         SCREAMING_SNAKE_CASE__								=attention_probs_dropout_prob
         SCREAMING_SNAKE_CASE__								=drop_path_rate
         SCREAMING_SNAKE_CASE__								=hidden_act
         SCREAMING_SNAKE_CASE__								=use_absolute_embeddings
         SCREAMING_SNAKE_CASE__								=patch_norm
         SCREAMING_SNAKE_CASE__								=layer_norm_eps
         SCREAMING_SNAKE_CASE__								=initializer_range
         SCREAMING_SNAKE_CASE__								=is_training
         SCREAMING_SNAKE_CASE__								=scope
         SCREAMING_SNAKE_CASE__								=use_labels
         SCREAMING_SNAKE_CASE__								=type_sequence_label_size
         SCREAMING_SNAKE_CASE__								=encoder_stride




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


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

         SCREAMING_SNAKE_CASE__								=None
         if self.use_labels:
             SCREAMING_SNAKE_CASE__								=ids_tensor([self.batch_size]				,self.type_sequence_label_size						)

         SCREAMING_SNAKE_CASE__								=self.get_config()

         return config, pixel_values, labels




     def   __A				(	self			: List[Any]						)		->   Union[str, Any]:


         '''simple docstring'''





         return DonutSwinConfig(
             image_size=self.image_size				,patch_size=self.patch_size				,num_channels=self.num_channels				,embed_dim=self.embed_dim				,depths=self.depths				,num_heads=self.num_heads				,window_size=self.window_size				,mlp_ratio=self.mlp_ratio				,qkv_bias=self.qkv_bias				,hidden_dropout_prob=self.hidden_dropout_prob				,attention_probs_dropout_prob=self.attention_probs_dropout_prob				,drop_path_rate=self.drop_path_rate				,hidden_act=self.hidden_act				,use_absolute_embeddings=self.use_absolute_embeddings				,path_norm=self.patch_norm				,layer_norm_eps=self.layer_norm_eps				,initializer_range=self.initializer_range				,encoder_stride=self.encoder_stride				,)




     def   __A				(	self			: List[str]				,_UpperCamelCase			: str				,_UpperCamelCase			: Optional[Any]				,_UpperCamelCase			: List[Any]						)		->   Optional[Any]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=DonutSwinModel(config=_UpperCamelCase						)
         model.to(_UpperCamelCase						)
         model.eval()
         SCREAMING_SNAKE_CASE__								=model(_UpperCamelCase						)

         SCREAMING_SNAKE_CASE__								=((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths						) - 1))
         SCREAMING_SNAKE_CASE__								=int(config.embed_dim * 2 ** (len(config.depths						) - 1)						)

         self.parent.assertEqual(result.last_hidden_state.shape				,(self.batch_size, expected_seq_len, expected_dim)						)




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


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=self.prepare_config_and_inputs()
         (
             (
             SCREAMING_SNAKE_CASE__
         )			,		(
             SCREAMING_SNAKE_CASE__
         )			,		(
             SCREAMING_SNAKE_CASE__
         )			,		
         )								=config_and_inputs
         SCREAMING_SNAKE_CASE__								={"""pixel_values""": pixel_values}
         return config, inputs_dict






@require_torch
class       __a					( __lowerCamelCase							,     __lowerCamelCase							,     unittest.TestCase     ):


     """simple docstring"""


     _A				:    List[Any]									=  (DonutSwinModel,) if is_torch_available() else ()
     _A				:    int									=  {"feature-extraction": DonutSwinModel} if is_torch_available() else {}
     _A				:    Union[str, Any]									=  True

     _A				:    Union[str, Any]									=  False
     _A				:    List[Any]									=  False
     _A				:    Any									=  False




     def   __A				(	self			: Any						)		->   List[str]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=DonutSwinModelTester(self						)
         SCREAMING_SNAKE_CASE__								=ConfigTester(self				,config_class=_UpperCamelCase				,embed_dim=3_7						)




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


         '''simple docstring'''





         self.create_and_test_config_common_properties()
         self.config_tester.create_and_test_config_to_json_string()
         self.config_tester.create_and_test_config_to_json_file()
         self.config_tester.create_and_test_config_from_and_save_pretrained()
         self.config_tester.create_and_test_config_with_num_labels()
         self.config_tester.check_config_can_be_init_without_params()
         self.config_tester.check_config_arguments_init()




     def   __A				(	self			: str						)		->   Any:


         '''simple docstring'''





         return




     def   __A				(	self			: Tuple						)		->   Optional[Any]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_UpperCamelCase						)




     def   __A				(	self			: Optional[int]						)		->   int:


         '''simple docstring'''





         pass




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


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__			,		SCREAMING_SNAKE_CASE__								=self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             SCREAMING_SNAKE_CASE__								=model_class(_UpperCamelCase						)
             self.assertIsInstance(model.get_input_embeddings()				,(nn.Module)						)
             SCREAMING_SNAKE_CASE__								=model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(_UpperCamelCase				,nn.Linear						)						)




     def   __A				(	self			: int						)		->   List[Any]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__			,		SCREAMING_SNAKE_CASE__								=self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             SCREAMING_SNAKE_CASE__								=model_class(_UpperCamelCase						)
             SCREAMING_SNAKE_CASE__								=inspect.signature(model.forward						)
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             SCREAMING_SNAKE_CASE__								=[*signature.parameters.keys()]

             SCREAMING_SNAKE_CASE__								=["""pixel_values"""]
             self.assertListEqual(arg_names[:1]				,_UpperCamelCase						)




     def   __A				(	self			: List[str]						)		->   Union[str, Any]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__			,		SCREAMING_SNAKE_CASE__								=self.model_tester.prepare_config_and_inputs_for_common()
         SCREAMING_SNAKE_CASE__								=True

         for model_class in self.all_model_classes:
             SCREAMING_SNAKE_CASE__								=True
             SCREAMING_SNAKE_CASE__								=False
             SCREAMING_SNAKE_CASE__								=True
             SCREAMING_SNAKE_CASE__								=model_class(_UpperCamelCase						)
             model.to(_UpperCamelCase						)
             model.eval()
             with torch.no_grad():
                 SCREAMING_SNAKE_CASE__								=model(**self._prepare_for_class(_UpperCamelCase				,_UpperCamelCase						)						)
             SCREAMING_SNAKE_CASE__								=outputs.attentions
             SCREAMING_SNAKE_CASE__								=len(self.model_tester.depths						)
             self.assertEqual(len(_UpperCamelCase						)				,_UpperCamelCase						)

             # check that output_attentions also work using config
             del inputs_dict["output_attentions"]
             SCREAMING_SNAKE_CASE__								=True
             SCREAMING_SNAKE_CASE__								=config.window_size**2
             SCREAMING_SNAKE_CASE__								=model_class(_UpperCamelCase						)
             model.to(_UpperCamelCase						)
             model.eval()
             with torch.no_grad():
                 SCREAMING_SNAKE_CASE__								=model(**self._prepare_for_class(_UpperCamelCase				,_UpperCamelCase						)						)
             SCREAMING_SNAKE_CASE__								=outputs.attentions
             self.assertEqual(len(_UpperCamelCase						)				,_UpperCamelCase						)

             self.assertListEqual(
                 list(attentions[0].shape[-3:]						)				,[self.model_tester.num_heads[0], window_size_squared, window_size_squared]				,)
             SCREAMING_SNAKE_CASE__								=len(_UpperCamelCase						)

             # Check attention is always last and order is fine
             SCREAMING_SNAKE_CASE__								=True
             SCREAMING_SNAKE_CASE__								=True
             SCREAMING_SNAKE_CASE__								=model_class(_UpperCamelCase						)
             model.to(_UpperCamelCase						)
             model.eval()
             with torch.no_grad():
                 SCREAMING_SNAKE_CASE__								=model(**self._prepare_for_class(_UpperCamelCase				,_UpperCamelCase						)						)

             if hasattr(self.model_tester				,"""num_hidden_states_types"""						):
                 SCREAMING_SNAKE_CASE__								=self.model_tester.num_hidden_states_types
             else:
                 # also another +1 for reshaped_hidden_states
                 SCREAMING_SNAKE_CASE__								=2
             self.assertEqual(out_len + added_hidden_states				,len(_UpperCamelCase						)						)

             SCREAMING_SNAKE_CASE__								=outputs.attentions

             self.assertEqual(len(_UpperCamelCase						)				,_UpperCamelCase						)

             self.assertListEqual(
                 list(self_attentions[0].shape[-3:]						)				,[self.model_tester.num_heads[0], window_size_squared, window_size_squared]				,)




     def   __A				(	self			: List[Any]				,_UpperCamelCase			: List[Any]				,_UpperCamelCase			: Dict				,_UpperCamelCase			: Dict				,_UpperCamelCase			: Union[str, Any]						)		->   Optional[int]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=model_class(_UpperCamelCase						)
         model.to(_UpperCamelCase						)
         model.eval()

         with torch.no_grad():
             SCREAMING_SNAKE_CASE__								=model(**self._prepare_for_class(_UpperCamelCase				,_UpperCamelCase						)						)

         SCREAMING_SNAKE_CASE__								=outputs.hidden_states

         SCREAMING_SNAKE_CASE__								=getattr(
             self.model_tester				,"""expected_num_hidden_layers"""				,len(self.model_tester.depths						) + 1						)
         self.assertEqual(len(_UpperCamelCase						)				,_UpperCamelCase						)

         # DonutSwin has a different seq_length
         SCREAMING_SNAKE_CASE__								=(
             config.patch_size
             if isinstance(config.patch_size				,collections.abc.Iterable						)
             else (config.patch_size, config.patch_size)
         )

         SCREAMING_SNAKE_CASE__								=(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

         self.assertListEqual(
             list(hidden_states[0].shape[-2:]						)				,[num_patches, self.model_tester.embed_dim]				,)

         SCREAMING_SNAKE_CASE__								=outputs.reshaped_hidden_states
         self.assertEqual(len(_UpperCamelCase						)				,_UpperCamelCase						)

         SCREAMING_SNAKE_CASE__			,		SCREAMING_SNAKE_CASE__			,		SCREAMING_SNAKE_CASE__			,		SCREAMING_SNAKE_CASE__								=reshaped_hidden_states[0].shape
         SCREAMING_SNAKE_CASE__								=(
             reshaped_hidden_states[0].view(_UpperCamelCase				,_UpperCamelCase				,height * width						).permute(0				,2				,1						)
         )
         self.assertListEqual(
             list(reshaped_hidden_states.shape[-2:]						)				,[num_patches, self.model_tester.embed_dim]				,)




     def   __A				(	self			: Dict						)		->   Dict:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__			,		SCREAMING_SNAKE_CASE__								=self.model_tester.prepare_config_and_inputs_for_common()

         SCREAMING_SNAKE_CASE__								=(
             self.model_tester.image_size
             if isinstance(self.model_tester.image_size				,collections.abc.Iterable						)
             else (self.model_tester.image_size, self.model_tester.image_size)
         )

         for model_class in self.all_model_classes:
             SCREAMING_SNAKE_CASE__								=True
             self.check_hidden_states_output(_UpperCamelCase				,_UpperCamelCase				,_UpperCamelCase				,_UpperCamelCase						)

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             SCREAMING_SNAKE_CASE__								=True

             self.check_hidden_states_output(_UpperCamelCase				,_UpperCamelCase				,_UpperCamelCase				,_UpperCamelCase						)




     def   __A				(	self			: Tuple						)		->   Union[str, Any]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__			,		SCREAMING_SNAKE_CASE__								=self.model_tester.prepare_config_and_inputs_for_common()
         SCREAMING_SNAKE_CASE__								=3

         SCREAMING_SNAKE_CASE__								=(
             self.model_tester.image_size
             if isinstance(self.model_tester.image_size				,collections.abc.Iterable						)
             else (self.model_tester.image_size, self.model_tester.image_size)
         )
         SCREAMING_SNAKE_CASE__								=(
             config.patch_size
             if isinstance(config.patch_size				,collections.abc.Iterable						)
             else (config.patch_size, config.patch_size)
         )

         SCREAMING_SNAKE_CASE__								=image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
         SCREAMING_SNAKE_CASE__								=image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

         for model_class in self.all_model_classes:
             SCREAMING_SNAKE_CASE__								=True
             self.check_hidden_states_output(_UpperCamelCase				,_UpperCamelCase				,_UpperCamelCase				,(padded_height, padded_width)						)

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             SCREAMING_SNAKE_CASE__								=True
             self.check_hidden_states_output(_UpperCamelCase				,_UpperCamelCase				,_UpperCamelCase				,(padded_height, padded_width)						)




     @slow
     def   __A				(	self			: Dict						)		->   List[str]:


         '''simple docstring'''





         for model_name in DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             SCREAMING_SNAKE_CASE__								=DonutSwinModel.from_pretrained(_UpperCamelCase						)
             self.assertIsNotNone(_UpperCamelCase						)




     def   __A				(	self			: List[Any]						)		->   Union[str, Any]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__			,		SCREAMING_SNAKE_CASE__								=self.model_tester.prepare_config_and_inputs_for_common()

         SCREAMING_SNAKE_CASE__								=_config_zero_init(_UpperCamelCase						)
         for model_class in self.all_model_classes:
             SCREAMING_SNAKE_CASE__								=model_class(config=_UpperCamelCase						)
             for name, param in model.named_parameters():
                 if "embeddings" not in name and param.requires_grad:
                     self.assertIn(
                         ((param.data.mean() * 1e9).round() / 1e9).item()				,[0.0, 1.0]				,msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""				,)












import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModelWithProjection

from diffusers import (
    AutoencoderKL,
    DPMSolverMultistepScheduler,
    PNDMScheduler,
    StableDiffusionImageVariationPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, nightly, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()
class       __a					( __lowerCamelCase							,     __lowerCamelCase							,     __lowerCamelCase							,     unittest.TestCase     ):


     """simple docstring"""


     _A				:    int									=  StableDiffusionImageVariationPipeline
     _A				:    List[str]									=  IMAGE_VARIATION_PARAMS
     _A				:    List[str]									=  IMAGE_VARIATION_BATCH_PARAMS
     _A				:    Any									=  frozenset([]     )
     # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
     _A				:    Tuple									=  frozenset([]     )




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


         '''simple docstring'''





         torch.manual_seed(0						)
         SCREAMING_SNAKE_CASE__								=UNetaDConditionModel(
             block_out_channels=(3_2, 6_4)				,layers_per_block=2				,sample_size=3_2				,in_channels=4				,out_channels=4				,down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")				,up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")				,cross_attention_dim=3_2				,)
         SCREAMING_SNAKE_CASE__								=PNDMScheduler(skip_prk_steps=_UpperCamelCase						)
         torch.manual_seed(0						)
         SCREAMING_SNAKE_CASE__								=AutoencoderKL(
             block_out_channels=[3_2, 6_4]				,in_channels=3				,out_channels=3				,down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]				,up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]				,latent_channels=4				,)
         torch.manual_seed(0						)
         SCREAMING_SNAKE_CASE__								=CLIPVisionConfig(
             hidden_size=3_2				,projection_dim=3_2				,intermediate_size=3_7				,layer_norm_eps=1e-05				,num_attention_heads=4				,num_hidden_layers=5				,image_size=3_2				,patch_size=4				,)
         SCREAMING_SNAKE_CASE__								=CLIPVisionModelWithProjection(_UpperCamelCase						)
         SCREAMING_SNAKE_CASE__								=CLIPImageProcessor(crop_size=3_2				,size=3_2						)

         SCREAMING_SNAKE_CASE__								={
             """unet""": unet,
             """scheduler""": scheduler,
             """vae""": vae,
             """image_encoder""": image_encoder,
             """feature_extractor""": feature_extractor,
             """safety_checker""": None,
         }
         return components




     def   __A				(	self			: str				,_UpperCamelCase			: Optional[int]				,_UpperCamelCase			: Union[str, Any]=0						)		->   Optional[Any]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=floats_tensor((1, 3, 3_2, 3_2)				,rng=random.Random(_UpperCamelCase						)						)
         SCREAMING_SNAKE_CASE__								=image.cpu().permute(0				,2				,3				,1						)[0]
         SCREAMING_SNAKE_CASE__								=Image.fromarray(np.uinta(_UpperCamelCase						)						).convert("""RGB"""						).resize((3_2, 3_2)						)
         if str(_UpperCamelCase						).startswith("""mps"""						):
             SCREAMING_SNAKE_CASE__								=torch.manual_seed(_UpperCamelCase						)
         else:
             SCREAMING_SNAKE_CASE__								=torch.Generator(device=_UpperCamelCase						).manual_seed(_UpperCamelCase						)
         SCREAMING_SNAKE_CASE__								={
             """image""": image,
             """generator""": generator,
             """num_inference_steps""": 2,
             """guidance_scale""": 6.0,
             """output_type""": """numpy""",
         }
         return inputs




     def   __A				(	self			: int						)		->   List[Any]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								="""cpu"""  # ensure determinism for the device-dependent torch.Generator
         SCREAMING_SNAKE_CASE__								=self.get_dummy_components()
         SCREAMING_SNAKE_CASE__								=StableDiffusionImageVariationPipeline(**_UpperCamelCase						)
         SCREAMING_SNAKE_CASE__								=sd_pipe.to(_UpperCamelCase						)
         sd_pipe.set_progress_bar_config(disable=_UpperCamelCase						)

         SCREAMING_SNAKE_CASE__								=self.get_dummy_inputs(_UpperCamelCase						)
         SCREAMING_SNAKE_CASE__								=sd_pipe(**_UpperCamelCase						).images
         SCREAMING_SNAKE_CASE__								=image[0, -3:, -3:, -1]

         assert image.shape == (1, 6_4, 6_4, 3)
         SCREAMING_SNAKE_CASE__								=np.array([0.5239, 0.5723, 0.4796, 0.5049, 0.5550, 0.4685, 0.5329, 0.4891, 0.4921]						)

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




     def   __A				(	self			: Tuple						)		->   Dict:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								="""cpu"""  # ensure determinism for the device-dependent torch.Generator
         SCREAMING_SNAKE_CASE__								=self.get_dummy_components()
         SCREAMING_SNAKE_CASE__								=StableDiffusionImageVariationPipeline(**_UpperCamelCase						)
         SCREAMING_SNAKE_CASE__								=sd_pipe.to(_UpperCamelCase						)
         sd_pipe.set_progress_bar_config(disable=_UpperCamelCase						)

         SCREAMING_SNAKE_CASE__								=self.get_dummy_inputs(_UpperCamelCase						)
         SCREAMING_SNAKE_CASE__								=2 * [inputs["""image"""]]
         SCREAMING_SNAKE_CASE__								=sd_pipe(**_UpperCamelCase						)

         SCREAMING_SNAKE_CASE__								=output.images

         SCREAMING_SNAKE_CASE__								=image[-1, -3:, -3:, -1]

         assert image.shape == (2, 6_4, 6_4, 3)
         SCREAMING_SNAKE_CASE__								=np.array([0.6892, 0.5637, 0.5836, 0.5771, 0.6254, 0.6409, 0.5580, 0.5569, 0.5289]						)

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




     def   __A				(	self			: Dict						)		->   Dict:


         '''simple docstring'''





         super().test_inference_batch_single_identical(expected_max_diff=3e-3						)






@slow
@require_torch_gpu
class       __a					( unittest.TestCase     ):


     """simple docstring"""


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


         '''simple docstring'''





         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()




     def   __A				(	self			: Optional[int]				,_UpperCamelCase			: Dict				,_UpperCamelCase			: Union[str, Any]="cpu"				,_UpperCamelCase			: Tuple=torch.floataa				,_UpperCamelCase			: List[Any]=0						)		->   List[Any]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=torch.Generator(device=_UpperCamelCase						).manual_seed(_UpperCamelCase						)
         SCREAMING_SNAKE_CASE__								=load_image(
             """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"""
             """/stable_diffusion_imgvar/input_image_vermeer.png"""						)
         SCREAMING_SNAKE_CASE__								=np.random.RandomState(_UpperCamelCase						).standard_normal((1, 4, 6_4, 6_4)						)
         SCREAMING_SNAKE_CASE__								=torch.from_numpy(_UpperCamelCase						).to(device=_UpperCamelCase				,dtype=_UpperCamelCase						)
         SCREAMING_SNAKE_CASE__								={
             """image""": init_image,
             """latents""": latents,
             """generator""": generator,
             """num_inference_steps""": 3,
             """guidance_scale""": 7.5,
             """output_type""": """numpy""",
         }
         return inputs




     def   __A				(	self			: List[Any]						)		->   int:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=StableDiffusionImageVariationPipeline.from_pretrained(
             """lambdalabs/sd-image-variations-diffusers"""				,safety_checker=_UpperCamelCase						)
         SCREAMING_SNAKE_CASE__								=sd_pipe.to(_UpperCamelCase						)
         sd_pipe.set_progress_bar_config(disable=_UpperCamelCase						)

         SCREAMING_SNAKE_CASE__								=self.get_inputs(_UpperCamelCase						)
         SCREAMING_SNAKE_CASE__								=sd_pipe(**_UpperCamelCase						).images
         SCREAMING_SNAKE_CASE__								=image[0, -3:, -3:, -1].flatten()

         assert image.shape == (1, 5_1_2, 5_1_2, 3)
         SCREAMING_SNAKE_CASE__								=np.array([0.8_4491, 0.9_0789, 0.7_5708, 0.7_8734, 0.8_3485, 0.7_0099, 0.6_6938, 0.6_8727, 0.6_1379]						)
         assert np.abs(image_slice - expected_slice						).max() < 6e-3




     def   __A				(	self			: Optional[int]						)		->   Dict:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=0

         def callback_fn(_UpperCamelCase			: int				,_UpperCamelCase			: int				,_UpperCamelCase			: torch.FloatTensor						) -> None:
             SCREAMING_SNAKE_CASE__								=True
             nonlocal number_of_steps
             number_of_steps += 1
             if step == 1:
                 SCREAMING_SNAKE_CASE__								=latents.detach().cpu().numpy()
                 assert latents.shape == (1, 4, 6_4, 6_4)
                 SCREAMING_SNAKE_CASE__								=latents[0, -3:, -3:, -1]
                 SCREAMING_SNAKE_CASE__								=np.array(
                     [-0.1621, 0.2837, -0.7979, -0.1221, -1.3057, 0.7681, -2.1191, 0.0464, 1.6309]						)

                 assert np.abs(latents_slice.flatten() - expected_slice						).max() < 5e-2
             elif step == 2:
                 SCREAMING_SNAKE_CASE__								=latents.detach().cpu().numpy()
                 assert latents.shape == (1, 4, 6_4, 6_4)
                 SCREAMING_SNAKE_CASE__								=latents[0, -3:, -3:, -1]
                 SCREAMING_SNAKE_CASE__								=np.array([0.6299, 1.7500, 1.1992, -2.1582, -1.8994, 0.7334, -0.7090, 1.0137, 1.5273]						)

                 assert np.abs(latents_slice.flatten() - expected_slice						).max() < 5e-2

         SCREAMING_SNAKE_CASE__								=False

         SCREAMING_SNAKE_CASE__								=StableDiffusionImageVariationPipeline.from_pretrained(
             """fusing/sd-image-variations-diffusers"""				,safety_checker=_UpperCamelCase				,torch_dtype=torch.floataa				,)
         pipe.to(_UpperCamelCase						)
         pipe.set_progress_bar_config(disable=_UpperCamelCase						)
         pipe.enable_attention_slicing()

         SCREAMING_SNAKE_CASE__								=self.get_inputs(_UpperCamelCase				,dtype=torch.floataa						)
         pipe(**_UpperCamelCase				,callback=_UpperCamelCase				,callback_steps=1						)
         assert callback_fn.has_been_called
         assert number_of_steps == inputs["num_inference_steps"]




     def   __A				(	self			: Union[str, Any]						)		->   Union[str, Any]:


         '''simple docstring'''





         torch.cuda.empty_cache()
         torch.cuda.reset_max_memory_allocated()
         torch.cuda.reset_peak_memory_stats()

         SCREAMING_SNAKE_CASE__								="""fusing/sd-image-variations-diffusers"""
         SCREAMING_SNAKE_CASE__								=StableDiffusionImageVariationPipeline.from_pretrained(
             _UpperCamelCase				,safety_checker=_UpperCamelCase				,torch_dtype=torch.floataa						)
         SCREAMING_SNAKE_CASE__								=pipe.to(_UpperCamelCase						)
         pipe.set_progress_bar_config(disable=_UpperCamelCase						)
         pipe.enable_attention_slicing(1						)
         pipe.enable_sequential_cpu_offload()

         SCREAMING_SNAKE_CASE__								=self.get_inputs(_UpperCamelCase				,dtype=torch.floataa						)
         SCREAMING_SNAKE_CASE__								=pipe(**_UpperCamelCase						)

         SCREAMING_SNAKE_CASE__								=torch.cuda.max_memory_allocated()
         # make sure that less than 2.6 GB is allocated
         assert mem_bytes < 2.6 * 1_0**9






@nightly
@require_torch_gpu
class       __a					( unittest.TestCase     ):


     """simple docstring"""


     def   __A				(	self			: Union[str, Any]						)		->   Any:


         '''simple docstring'''





         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()




     def   __A				(	self			: Dict				,_UpperCamelCase			: List[str]				,_UpperCamelCase			: Union[str, Any]="cpu"				,_UpperCamelCase			: Any=torch.floataa				,_UpperCamelCase			: Tuple=0						)		->   Any:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=torch.Generator(device=_UpperCamelCase						).manual_seed(_UpperCamelCase						)
         SCREAMING_SNAKE_CASE__								=load_image(
             """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"""
             """/stable_diffusion_imgvar/input_image_vermeer.png"""						)
         SCREAMING_SNAKE_CASE__								=np.random.RandomState(_UpperCamelCase						).standard_normal((1, 4, 6_4, 6_4)						)
         SCREAMING_SNAKE_CASE__								=torch.from_numpy(_UpperCamelCase						).to(device=_UpperCamelCase				,dtype=_UpperCamelCase						)
         SCREAMING_SNAKE_CASE__								={
             """image""": init_image,
             """latents""": latents,
             """generator""": generator,
             """num_inference_steps""": 5_0,
             """guidance_scale""": 7.5,
             """output_type""": """numpy""",
         }
         return inputs




     def   __A				(	self			: Dict						)		->   str:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=StableDiffusionImageVariationPipeline.from_pretrained("""fusing/sd-image-variations-diffusers"""						)
         sd_pipe.to(_UpperCamelCase						)
         sd_pipe.set_progress_bar_config(disable=_UpperCamelCase						)

         SCREAMING_SNAKE_CASE__								=self.get_inputs(_UpperCamelCase						)
         SCREAMING_SNAKE_CASE__								=sd_pipe(**_UpperCamelCase						).images[0]

         SCREAMING_SNAKE_CASE__								=load_numpy(
             """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"""
             """/stable_diffusion_imgvar/lambdalabs_variations_pndm.npy"""						)
         SCREAMING_SNAKE_CASE__								=np.abs(expected_image - image						).max()
         assert max_diff < 1e-3




     def   __A				(	self			: List[str]						)		->   Tuple:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=StableDiffusionImageVariationPipeline.from_pretrained("""fusing/sd-image-variations-diffusers"""						)
         SCREAMING_SNAKE_CASE__								=DPMSolverMultistepScheduler.from_config(sd_pipe.scheduler.config						)
         sd_pipe.to(_UpperCamelCase						)
         sd_pipe.set_progress_bar_config(disable=_UpperCamelCase						)

         SCREAMING_SNAKE_CASE__								=self.get_inputs(_UpperCamelCase						)
         SCREAMING_SNAKE_CASE__								=2_5
         SCREAMING_SNAKE_CASE__								=sd_pipe(**_UpperCamelCase						).images[0]

         SCREAMING_SNAKE_CASE__								=load_numpy(
             """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"""
             """/stable_diffusion_imgvar/lambdalabs_variations_dpm_multi.npy"""						)
         SCREAMING_SNAKE_CASE__								=np.abs(expected_image - image						).max()
         assert max_diff < 1e-3






