'''simple docstring'''

import collections.abc
from typing import Optional, Tuple, Union

import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_poolformer import PoolFormerConfig


lowercase_     		= logging.get_logger(__name__)

# General docstring
lowercase_     		= '''PoolFormerConfig'''

# Base docstring
lowercase_     		= '''sail/poolformer_s12'''
lowercase_     		= [1, 512, 7, 7]

# Image classification docstring
lowercase_     		= '''sail/poolformer_s12'''
lowercase_     		= '''tabby, tabby cat'''

lowercase_     		= [
    '''sail/poolformer_s12''',
    # See all PoolFormer models at https://huggingface.co/models?filter=poolformer
]



def 							UpperCamelCase__			(			a__			,      a__ = 0.0			,      a__ = False      ):


						'''simple docstring'''






						if drop_prob == 0.0 or not training:
												return input
						_lowerCAmelCase										=1 - drop_prob
						_lowerCAmelCase										=(input.shape[0],) + (1,) * (input.ndim - 1)  # work with diff dim tensors, not just 2D ConvNets
						_lowerCAmelCase										=keep_prob + torch.rand(_lowerCamelCase			,      dtype=input.dtype			,      device=input.device      )
						random_tensor.floor_()  # binarize
						_lowerCAmelCase										=input.div(_lowerCamelCase      ) * random_tensor
						return output
class   SCREAMING_SNAKE_CASE			(						nn.Module):







		"""simple docstring"""






		def __init__(   self		,						__A = None				) ->     str:
								super().__init__()
								_lowerCAmelCase										=drop_prob






		def 		UpperCamelCase__       (   self		,						__A				) ->     int:
								return drop_path(_A		,						self.drop_prob		,						self.training				)






		def 		UpperCamelCase__       (   self				) ->     Tuple:
								return "p={}".format(self.drop_prob				)

class   SCREAMING_SNAKE_CASE			(						nn.Module):







		"""simple docstring"""






		def __init__(   self		,						__A		,						__A		,						__A		,						__A		,						__A		,						__A=None				) ->     Dict:
								super().__init__()
								_lowerCAmelCase										=patch_size if isinstance(_A		,						collections.abc.Iterable				) else (patch_size, patch_size)
								_lowerCAmelCase										=stride if isinstance(_A		,						collections.abc.Iterable				) else (stride, stride)
								_lowerCAmelCase										=padding if isinstance(_A		,						collections.abc.Iterable				) else (padding, padding)

								_lowerCAmelCase										=nn.Convad(_A		,						_A		,						kernel_size=_A		,						stride=_A		,						padding=_A				)
								_lowerCAmelCase										=norm_layer(_A				) if norm_layer else nn.Identity()






		def 		UpperCamelCase__       (   self		,						__A				) ->     Optional[int]:
								_lowerCAmelCase										=self.projection(_A				)
								_lowerCAmelCase										=self.norm(_A				)
								return embeddings

class   SCREAMING_SNAKE_CASE			(						nn.GroupNorm):







		"""simple docstring"""






		def __init__(   self		,						__A		,						**__A				) ->     str:
								super().__init__(1		,						_A		,						**_A				)

class   SCREAMING_SNAKE_CASE			(						nn.Module):







		"""simple docstring"""






		def __init__(   self		,						__A				) ->     List[Any]:
								super().__init__()
								_lowerCAmelCase										=nn.AvgPoolad(_A		,						stride=1		,						padding=pool_size // 2		,						count_include_pad=_A				)






		def 		UpperCamelCase__       (   self		,						__A				) ->     str:
								return self.pool(_A				) - hidden_states

class   SCREAMING_SNAKE_CASE			(						nn.Module):







		"""simple docstring"""






		def __init__(   self		,						__A		,						__A		,						__A		,						__A				) ->     Tuple:
								super().__init__()
								_lowerCAmelCase										=nn.Convad(_A		,						_A		,						1				)
								_lowerCAmelCase										=nn.Convad(_A		,						_A		,						1				)
								_lowerCAmelCase										=PoolFormerDropPath(_A				)
								if isinstance(config.hidden_act		,						_A				):
														_lowerCAmelCase										=ACTaFN[config.hidden_act]
								else:
														_lowerCAmelCase										=config.hidden_act






		def 		UpperCamelCase__       (   self		,						__A				) ->     Tuple:
								_lowerCAmelCase										=self.conva(_A				)
								_lowerCAmelCase										=self.act_fn(_A				)
								_lowerCAmelCase										=self.drop(_A				)
								_lowerCAmelCase										=self.conva(_A				)
								_lowerCAmelCase										=self.drop(_A				)

								return hidden_states

class   SCREAMING_SNAKE_CASE			(						nn.Module):







		"""simple docstring"""






		def __init__(   self		,						__A		,						__A		,						__A		,						__A		,						__A		,						__A				) ->     str:
								super().__init__()
								_lowerCAmelCase										=PoolFormerPooling(_A				)
								_lowerCAmelCase										=PoolFormerOutput(_A		,						_A		,						_A		,						_A				)
								_lowerCAmelCase										=PoolFormerGroupNorm(_A				)
								_lowerCAmelCase										=PoolFormerGroupNorm(_A				)

								# Useful for training neural nets
								_lowerCAmelCase										=PoolFormerDropPath(_A				) if drop_path > 0.0 else nn.Identity()
								_lowerCAmelCase										=config.use_layer_scale
								if config.use_layer_scale:
														_lowerCAmelCase										=nn.Parameter(
														    config.layer_scale_init_value * torch.ones((_A)				)		,						requires_grad=_A				)
														_lowerCAmelCase										=nn.Parameter(
														    config.layer_scale_init_value * torch.ones((_A)				)		,						requires_grad=_A				)






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

								if self.use_layer_scale:
														_lowerCAmelCase										=self.pooling(self.before_norm(_A				)				)
														_lowerCAmelCase										=self.layer_scale_a.unsqueeze(-1				).unsqueeze(-1				) * pooling_output
														# First residual connection
														_lowerCAmelCase										=hidden_states + self.drop_path(_A				)
														_lowerCAmelCase										=()

														_lowerCAmelCase										=self.output(self.after_norm(_A				)				)
														_lowerCAmelCase										=self.layer_scale_a.unsqueeze(-1				).unsqueeze(-1				) * layer_output
														# Second residual connection
														_lowerCAmelCase										=hidden_states + self.drop_path(_A				)

														_lowerCAmelCase										=(output,) + outputs
														return outputs

								else:
														_lowerCAmelCase										=self.drop_path(self.pooling(self.before_norm(_A				)				)				)
														# First residual connection
														_lowerCAmelCase										=pooling_output + hidden_states
														_lowerCAmelCase										=()

														# Second residual connection inside the PoolFormerOutput block
														_lowerCAmelCase										=self.drop_path(self.output(self.after_norm(_A				)				)				)
														_lowerCAmelCase										=hidden_states + layer_output

														_lowerCAmelCase										=(output,) + outputs
														return outputs

class   SCREAMING_SNAKE_CASE			(						nn.Module):







		"""simple docstring"""






		def __init__(   self		,						__A				) ->     Dict:
								super().__init__()
								_lowerCAmelCase										=config
								# stochastic depth decay rule
								_lowerCAmelCase										=[x.item() for x in torch.linspace(0		,						config.drop_path_rate		,						sum(config.depths				)				)]

								# patch embeddings
								_lowerCAmelCase										=[]
								for i in range(config.num_encoder_blocks				):
														embeddings.append(
														    PoolFormerEmbeddings(
														        patch_size=config.patch_sizes[i]		,						stride=config.strides[i]		,						padding=config.padding[i]		,						num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1]		,						hidden_size=config.hidden_sizes[i]		,						)				)
								_lowerCAmelCase										=nn.ModuleList(_A				)

								# Transformer blocks
								_lowerCAmelCase										=[]
								_lowerCAmelCase										=0
								for i in range(config.num_encoder_blocks				):
														# each block consists of layers
														_lowerCAmelCase										=[]
														if i != 0:
																				cur += config.depths[i - 1]
														for j in range(config.depths[i]				):
																				layers.append(
																				    PoolFormerLayer(
																				        _A		,						num_channels=config.hidden_sizes[i]		,						pool_size=config.pool_size		,						hidden_size=config.hidden_sizes[i]		,						intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio				)		,						drop_path=dpr[cur + j]		,						)				)
														blocks.append(nn.ModuleList(_A				)				)

								_lowerCAmelCase										=nn.ModuleList(_A				)






		def 		UpperCamelCase__       (   self		,						__A		,						__A=False		,						__A=True				) ->     Optional[int]:
								_lowerCAmelCase										=() if output_hidden_states else None

								_lowerCAmelCase										=pixel_values
								for idx, layers in enumerate(zip(self.patch_embeddings		,						self.block				)				):
														_lowerCAmelCase										=layers
														# Get patch embeddings from hidden_states
														_lowerCAmelCase										=embedding_layer(_A				)
														# Send the embeddings through the blocks
														for _, blk in enumerate(_A				):
																				_lowerCAmelCase										=blk(_A				)
																				_lowerCAmelCase										=layer_outputs[0]

														if output_hidden_states:
																				_lowerCAmelCase										=all_hidden_states + (hidden_states,)

								if not return_dict:
														return tuple(v for v in [hidden_states, all_hidden_states] if v is not None				)

								return BaseModelOutputWithNoAttention(last_hidden_state=_A		,						hidden_states=_A				)

class   SCREAMING_SNAKE_CASE			(						a__):







		"""simple docstring"""
		lowercase   :      Dict       =							PoolFormerConfig
		lowercase   :      int       =							'poolformer'
		lowercase   :      Tuple       =							'pixel_values'
		lowercase   :      Optional[Any]       =							True






		def 		UpperCamelCase__       (   self		,						__A				) ->     str:

								if isinstance(_A		,						(nn.Linear, nn.Convad)				):
														module.weight.data.normal_(mean=0.0		,						std=self.config.initializer_range				)
														if module.bias is not None:
																				module.bias.data.zero_()
								elif isinstance(_A		,						nn.LayerNorm				):
														module.bias.data.zero_()
														module.weight.data.fill_(1.0				)






		def 		UpperCamelCase__       (   self		,						__A		,						__A=False				) ->     Any:

								if isinstance(_A		,						_A				):
														_lowerCAmelCase										=value

lowercase_     		= r'''
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
'''

lowercase_     		= r'''
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`PoolFormerImageProcessor.__call__`] for details.
'''
@add_start_docstrings(
    'The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.'    ,			a__    ,			)
class   SCREAMING_SNAKE_CASE			(						a__):







		"""simple docstring"""






		def __init__(   self		,						__A				) ->     List[Any]:
								super().__init__(_A				)
								_lowerCAmelCase										=config

								_lowerCAmelCase										=PoolFormerEncoder(_A				)

								# Initialize weights and apply final processing
								self.post_init()






		def 		UpperCamelCase__       (   self				) ->     Tuple:
								return self.embeddings.patch_embeddings






		@add_start_docstrings_to_model_forward(_A				)
		@add_code_sample_docstrings(
		    checkpoint=_CHECKPOINT_FOR_DOC		,						output_type=_A		,						config_class=_CONFIG_FOR_DOC		,						modality='vision'		,						expected_output=_EXPECTED_OUTPUT_SHAPE		,						)
		def 		UpperCamelCase__       (   self		,						__A = None		,						__A = None		,						__A = None		,						) ->     List[str]:
								_lowerCAmelCase										=(
								    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
								)
								_lowerCAmelCase										=return_dict if return_dict is not None else self.config.use_return_dict

								if pixel_values is None:
														raise ValueError('You have to specify pixel_values'				)

								_lowerCAmelCase										=self.encoder(
								    _A		,						output_hidden_states=_A		,						return_dict=_A		,						)
								_lowerCAmelCase										=encoder_outputs[0]

								if not return_dict:
														return (sequence_output, None) + encoder_outputs[1:]

								return BaseModelOutputWithNoAttention(
								    last_hidden_state=_A		,						hidden_states=encoder_outputs.hidden_states		,						)

class   SCREAMING_SNAKE_CASE			(						nn.Module):







		"""simple docstring"""






		def __init__(   self		,						__A				) ->     Optional[Any]:
								super().__init__()
								_lowerCAmelCase										=nn.Linear(config.hidden_size		,						config.hidden_size				)






		def 		UpperCamelCase__       (   self		,						__A				) ->     Optional[int]:
								_lowerCAmelCase										=self.dense(_A				)
								return output

@add_start_docstrings(
    '\n    PoolFormer Model transformer with an image classification head on top\n    '    ,			a__    ,			)
class   SCREAMING_SNAKE_CASE			(						a__):







		"""simple docstring"""






		def __init__(   self		,						__A				) ->     List[Any]:
								super().__init__(_A				)
								_lowerCAmelCase										=config.num_labels
								_lowerCAmelCase										=PoolFormerModel(_A				)

								# Final norm
								_lowerCAmelCase										=PoolFormerGroupNorm(config.hidden_sizes[-1]				)
								# Classifier head
								_lowerCAmelCase										=(
								    nn.Linear(config.hidden_sizes[-1]		,						config.num_labels				) if config.num_labels > 0 else nn.Identity()
								)

								# Initialize weights and apply final processing
								self.post_init()






		@add_start_docstrings_to_model_forward(_A				)
		@add_code_sample_docstrings(
		    checkpoint=_IMAGE_CLASS_CHECKPOINT		,						output_type=_A		,						config_class=_CONFIG_FOR_DOC		,						expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT		,						)
		def 		UpperCamelCase__       (   self		,						__A = None		,						__A = None		,						__A = None		,						__A = None		,						) ->     List[str]:
								_lowerCAmelCase										=return_dict if return_dict is not None else self.config.use_return_dict

								_lowerCAmelCase										=self.poolformer(
								    _A		,						output_hidden_states=_A		,						return_dict=_A		,						)

								_lowerCAmelCase										=outputs[0]

								_lowerCAmelCase										=self.classifier(self.norm(_A				).mean([-2, -1]				)				)

								_lowerCAmelCase										=None
								if labels is not None:
														if self.config.problem_type is None:
																				if self.num_labels == 1:
																										_lowerCAmelCase										='regression'
																				elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
																										_lowerCAmelCase										='single_label_classification'
																				else:
																										_lowerCAmelCase										='multi_label_classification'

														if self.config.problem_type == "regression":
																				_lowerCAmelCase										=MSELoss()
																				if self.num_labels == 1:
																										_lowerCAmelCase										=loss_fct(logits.squeeze()		,						labels.squeeze()				)
																				else:
																										_lowerCAmelCase										=loss_fct(_A		,						_A				)
														elif self.config.problem_type == "single_label_classification":
																				_lowerCAmelCase										=CrossEntropyLoss()
																				_lowerCAmelCase										=loss_fct(logits.view(-1		,						self.num_labels				)		,						labels.view(-1				)				)
														elif self.config.problem_type == "multi_label_classification":
																				_lowerCAmelCase										=BCEWithLogitsLoss()
																				_lowerCAmelCase										=loss_fct(_A		,						_A				)

								if not return_dict:
														_lowerCAmelCase										=(logits,) + outputs[2:]
														return ((loss,) + output) if loss is not None else output

								return ImageClassifierOutputWithNoAttention(loss=_A		,						logits=_A		,						hidden_states=outputs.hidden_states				)



'''simple docstring'''

import gc
import random
import unittest

import torch

from diffusers import (
    IFImgaImgPipeline,
    IFImgaImgSuperResolutionPipeline,
    IFInpaintingPipeline,
    IFInpaintingSuperResolutionPipeline,
    IFPipeline,
    IFSuperResolutionPipeline,
)
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
from . import IFPipelineTesterMixin
@skip_mps
class   SCREAMING_SNAKE_CASE			(						__lowercase    ,			__lowercase    ,			unittest.TestCase):







		"""simple docstring"""
		lowercase   :      List[Any]       =							IFPipeline
		lowercase   :      Tuple       =							TEXT_TO_IMAGE_PARAMS - {'width', 'height', 'latents'}
		lowercase   :      Union[str, Any]       =							TEXT_TO_IMAGE_BATCH_PARAMS
		lowercase   :      int       =							PipelineTesterMixin.required_optional_params - {'latents'}






		def 		UpperCamelCase__       (   self				) ->     str:
								return self._get_dummy_components()






		def 		UpperCamelCase__       (   self		,						__A		,						__A=0				) ->     int:
								if str(__A				).startswith('mps'				):
														_lowerCAmelCase										=torch.manual_seed(__A				)
								else:
														_lowerCAmelCase										=torch.Generator(device=__A				).manual_seed(__A				)

								_lowerCAmelCase										={
								    'prompt': 'A painting of a squirrel eating a burger',
								    'generator': generator,
								    'num_inference_steps': 2,
								    'output_type': 'numpy',
								}

								return inputs






		def 		UpperCamelCase__       (   self				) ->     Optional[Any]:
								self._test_save_load_optional_components()






		@unittest.skipIf(torch_device != 'cuda'		,						reason='float16 requires CUDA'				)
		def 		UpperCamelCase__       (   self				) ->     Tuple:
								# 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				)






		def 		UpperCamelCase__       (   self				) ->     List[Any]:
								self._test_attention_slicing_forward_pass(expected_max_diff=1E-2				)






		def 		UpperCamelCase__       (   self				) ->     str:
								self._test_save_load_local()






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






		@unittest.skipIf(
		    torch_device != 'cuda' or not is_xformers_available()		,						reason='XFormers attention is only available with CUDA and `xformers` installed'		,						)
		def 		UpperCamelCase__       (   self				) ->     List[str]:
								self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3				)

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







		"""simple docstring"""






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






		def 		UpperCamelCase__       (   self				) ->     Optional[Any]:
								# if

								_lowerCAmelCase										=IFPipeline.from_pretrained('DeepFloyd/IF-I-XL-v1.0'		,						variant='fp16'		,						torch_dtype=torch.floataa				)

								_lowerCAmelCase										=IFSuperResolutionPipeline.from_pretrained(
								    'DeepFloyd/IF-II-L-v1.0'		,						variant='fp16'		,						torch_dtype=torch.floataa		,						text_encoder=__A		,						tokenizer=__A				)

								# pre compute text embeddings and remove T5 to save memory

								pipe_a.text_encoder.to('cuda'				)

								_lowerCAmelCase						,				_lowerCAmelCase										=pipe_a.encode_prompt('anime turtle'		,						device='cuda'				)

								del pipe_a.tokenizer
								del pipe_a.text_encoder
								gc.collect()

								_lowerCAmelCase										=None
								_lowerCAmelCase										=None

								pipe_a.enable_model_cpu_offload()
								pipe_a.enable_model_cpu_offload()

								pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()				)
								pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()				)

								self._test_if(__A		,						__A		,						__A		,						__A				)

								pipe_a.remove_all_hooks()
								pipe_a.remove_all_hooks()

								# img2img

								_lowerCAmelCase										=IFImgaImgPipeline(**pipe_a.components				)
								_lowerCAmelCase										=IFImgaImgSuperResolutionPipeline(**pipe_a.components				)

								pipe_a.enable_model_cpu_offload()
								pipe_a.enable_model_cpu_offload()

								pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()				)
								pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()				)

								self._test_if_imgaimg(__A		,						__A		,						__A		,						__A				)

								pipe_a.remove_all_hooks()
								pipe_a.remove_all_hooks()

								# inpainting

								_lowerCAmelCase										=IFInpaintingPipeline(**pipe_a.components				)
								_lowerCAmelCase										=IFInpaintingSuperResolutionPipeline(**pipe_a.components				)

								pipe_a.enable_model_cpu_offload()
								pipe_a.enable_model_cpu_offload()

								pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()				)
								pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()				)

								self._test_if_inpainting(__A		,						__A		,						__A		,						__A				)






		def 		UpperCamelCase__       (   self		,						__A		,						__A		,						__A		,						__A				) ->     str:
								# pipeline 1

								_start_torch_memory_measurement()

								_lowerCAmelCase										=torch.Generator(device='cpu'				).manual_seed(0				)
								_lowerCAmelCase										=pipe_a(
								    prompt_embeds=__A		,						negative_prompt_embeds=__A		,						num_inference_steps=2		,						generator=__A		,						output_type='np'		,						)

								_lowerCAmelCase										=output.images[0]

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

								_lowerCAmelCase										=torch.cuda.max_memory_allocated()
								assert mem_bytes < 13 * 10**9

								_lowerCAmelCase										=load_numpy(
								    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy'				)
								assert_mean_pixel_difference(__A		,						__A				)

								# pipeline 2

								_start_torch_memory_measurement()

								_lowerCAmelCase										=torch.Generator(device='cpu'				).manual_seed(0				)

								_lowerCAmelCase										=floats_tensor((1, 3, 64, 64)		,						rng=random.Random(0				)				).to(__A				)

								_lowerCAmelCase										=pipe_a(
								    prompt_embeds=__A		,						negative_prompt_embeds=__A		,						image=__A		,						generator=__A		,						num_inference_steps=2		,						output_type='np'		,						)

								_lowerCAmelCase										=output.images[0]

								assert image.shape == (256, 256, 3)

								_lowerCAmelCase										=torch.cuda.max_memory_allocated()
								assert mem_bytes < 4 * 10**9

								_lowerCAmelCase										=load_numpy(
								    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy'				)
								assert_mean_pixel_difference(__A		,						__A				)






		def 		UpperCamelCase__       (   self		,						__A		,						__A		,						__A		,						__A				) ->     Optional[int]:
								# pipeline 1

								_start_torch_memory_measurement()

								_lowerCAmelCase										=floats_tensor((1, 3, 64, 64)		,						rng=random.Random(0				)				).to(__A				)

								_lowerCAmelCase										=torch.Generator(device='cpu'				).manual_seed(0				)

								_lowerCAmelCase										=pipe_a(
								    prompt_embeds=__A		,						negative_prompt_embeds=__A		,						image=__A		,						num_inference_steps=2		,						generator=__A		,						output_type='np'		,						)

								_lowerCAmelCase										=output.images[0]

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

								_lowerCAmelCase										=torch.cuda.max_memory_allocated()
								assert mem_bytes < 10 * 10**9

								_lowerCAmelCase										=load_numpy(
								    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy'				)
								assert_mean_pixel_difference(__A		,						__A				)

								# pipeline 2

								_start_torch_memory_measurement()

								_lowerCAmelCase										=torch.Generator(device='cpu'				).manual_seed(0				)

								_lowerCAmelCase										=floats_tensor((1, 3, 256, 256)		,						rng=random.Random(0				)				).to(__A				)
								_lowerCAmelCase										=floats_tensor((1, 3, 64, 64)		,						rng=random.Random(0				)				).to(__A				)

								_lowerCAmelCase										=pipe_a(
								    prompt_embeds=__A		,						negative_prompt_embeds=__A		,						image=__A		,						original_image=__A		,						generator=__A		,						num_inference_steps=2		,						output_type='np'		,						)

								_lowerCAmelCase										=output.images[0]

								assert image.shape == (256, 256, 3)

								_lowerCAmelCase										=torch.cuda.max_memory_allocated()
								assert mem_bytes < 4 * 10**9

								_lowerCAmelCase										=load_numpy(
								    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy'				)
								assert_mean_pixel_difference(__A		,						__A				)






		def 		UpperCamelCase__       (   self		,						__A		,						__A		,						__A		,						__A				) ->     Dict:
								# pipeline 1

								_start_torch_memory_measurement()

								_lowerCAmelCase										=floats_tensor((1, 3, 64, 64)		,						rng=random.Random(0				)				).to(__A				)
								_lowerCAmelCase										=floats_tensor((1, 3, 64, 64)		,						rng=random.Random(1				)				).to(__A				)

								_lowerCAmelCase										=torch.Generator(device='cpu'				).manual_seed(0				)
								_lowerCAmelCase										=pipe_a(
								    prompt_embeds=__A		,						negative_prompt_embeds=__A		,						image=__A		,						mask_image=__A		,						num_inference_steps=2		,						generator=__A		,						output_type='np'		,						)

								_lowerCAmelCase										=output.images[0]

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

								_lowerCAmelCase										=torch.cuda.max_memory_allocated()
								assert mem_bytes < 10 * 10**9

								_lowerCAmelCase										=load_numpy(
								    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy'				)
								assert_mean_pixel_difference(__A		,						__A				)

								# pipeline 2

								_start_torch_memory_measurement()

								_lowerCAmelCase										=torch.Generator(device='cpu'				).manual_seed(0				)

								_lowerCAmelCase										=floats_tensor((1, 3, 64, 64)		,						rng=random.Random(0				)				).to(__A				)
								_lowerCAmelCase										=floats_tensor((1, 3, 256, 256)		,						rng=random.Random(0				)				).to(__A				)
								_lowerCAmelCase										=floats_tensor((1, 3, 256, 256)		,						rng=random.Random(1				)				).to(__A				)

								_lowerCAmelCase										=pipe_a(
								    prompt_embeds=__A		,						negative_prompt_embeds=__A		,						image=__A		,						mask_image=__A		,						original_image=__A		,						generator=__A		,						num_inference_steps=2		,						output_type='np'		,						)

								_lowerCAmelCase										=output.images[0]

								assert image.shape == (256, 256, 3)

								_lowerCAmelCase										=torch.cuda.max_memory_allocated()
								assert mem_bytes < 4 * 10**9

								_lowerCAmelCase										=load_numpy(
								    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy'				)
								assert_mean_pixel_difference(__A		,						__A				)



def 							UpperCamelCase__			(			):


						'''simple docstring'''






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





