



from typing import Optional

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

from ...activations import ACTaFN
from ...modeling_outputs import (
    BackboneOutput,
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import (
    add_code_sample_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    logging,
    replace_return_docstrings,
)
from ...utils.backbone_utils import BackboneMixin
from .configuration_resnet import ResNetConfig


_lowercase						  =		logging.get_logger(__name__)

# General docstring
_lowercase						  =		"ResNetConfig"

# Base docstring
_lowercase						  =		"microsoft/resnet-50"
_lowercase						  =		[1, 2048, 7, 7]

# Image classification docstring
_lowercase						  =		"microsoft/resnet-50"
_lowercase						  =		"tiger cat"

_lowercase						  =		[
    "microsoft/resnet-50",
    # See all resnet models at https://huggingface.co/models?filter=resnet
]



class     _UpperCAmelCase			(       nn.Module     ):




     def __init__(				self ,						a__ ,						a__ ,						a__ = 3 ,						a__ = 1 ,						a__ = "relu"):
         super().__init__()
         A__		 =					nn.Convad(
             a__ ,						a__ ,						kernel_size=a__ ,						stride=a__ ,						padding=kernel_size // 2 ,						bias=a__)
         A__		 =					nn.BatchNormad(a__)
         A__		 =					ACTaFN[activation] if activation is not None else nn.Identity()




     def 		snake_case_		(				self ,						a__):
         A__		 =					self.convolution(a__)
         A__		 =					self.normalization(a__)
         A__		 =					self.activation(a__)
         return hidden_state







class     _UpperCAmelCase			(       nn.Module     ):




     def __init__(				self ,						a__):
         super().__init__()
         A__		 =					ResNetConvLayer(
             config.num_channels ,						config.embedding_size ,						kernel_size=7 ,						stride=2 ,						activation=config.hidden_act)
         A__		 =					nn.MaxPoolad(kernel_size=3 ,						stride=2 ,						padding=1)
         A__		 =					config.num_channels




     def 		snake_case_		(				self ,						a__):
         A__		 =					pixel_values.shape[1]
         if num_channels != self.num_channels:
             raise ValueError(
                 '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.''')
         A__		 =					self.embedder(a__)
         A__		 =					self.pooler(a__)
         return embedding







class     _UpperCAmelCase			(       nn.Module     ):




     def __init__(				self ,						a__ ,						a__ ,						a__ = 2):
         super().__init__()
         A__		 =					nn.Convad(a__ ,						a__ ,						kernel_size=1 ,						stride=a__ ,						bias=a__)
         A__		 =					nn.BatchNormad(a__)




     def 		snake_case_		(				self ,						a__):
         A__		 =					self.convolution(a__)
         A__		 =					self.normalization(a__)
         return hidden_state







class     _UpperCAmelCase			(       nn.Module     ):




     def __init__(				self ,						a__ ,						a__ ,						a__ = 1 ,						a__ = "relu"):
         super().__init__()
         A__		 =					in_channels != out_channels or stride != 1
         A__		 =					(
             ResNetShortCut(a__ ,						a__ ,						stride=a__) if should_apply_shortcut else nn.Identity()
         )
         A__		 =					nn.Sequential(
             ResNetConvLayer(a__ ,						a__ ,						stride=a__) ,						ResNetConvLayer(a__ ,						a__ ,						activation=a__) ,						)
         A__		 =					ACTaFN[activation]




     def 		snake_case_		(				self ,						a__):
         A__		 =					hidden_state
         A__		 =					self.layer(a__)
         A__		 =					self.shortcut(a__)
         hidden_state += residual
         A__		 =					self.activation(a__)
         return hidden_state







class     _UpperCAmelCase			(       nn.Module     ):




     def __init__(				self ,						a__ ,						a__ ,						a__ = 1 ,						a__ = "relu" ,						a__ = 4):
         super().__init__()
         A__		 =					in_channels != out_channels or stride != 1
         A__		 =					out_channels // reduction
         A__		 =					(
             ResNetShortCut(a__ ,						a__ ,						stride=a__) if should_apply_shortcut else nn.Identity()
         )
         A__		 =					nn.Sequential(
             ResNetConvLayer(a__ ,						a__ ,						kernel_size=1) ,						ResNetConvLayer(a__ ,						a__ ,						stride=a__) ,						ResNetConvLayer(a__ ,						a__ ,						kernel_size=1 ,						activation=a__) ,						)
         A__		 =					ACTaFN[activation]




     def 		snake_case_		(				self ,						a__):
         A__		 =					hidden_state
         A__		 =					self.layer(a__)
         A__		 =					self.shortcut(a__)
         hidden_state += residual
         A__		 =					self.activation(a__)
         return hidden_state







class     _UpperCAmelCase			(       nn.Module     ):




     def __init__(				self ,						a__ ,						a__ ,						a__ ,						a__ = 2 ,						a__ = 2 ,						):
         super().__init__()

         A__		 =					ResNetBottleNeckLayer if config.layer_type == '''bottleneck''' else ResNetBasicLayer

         A__		 =					nn.Sequential(
             # downsampling is done in the first layer with stride of 2
             layer(a__ ,						a__ ,						stride=a__ ,						activation=config.hidden_act) ,						*[layer(a__ ,						a__ ,						activation=config.hidden_act) for _ in range(depth - 1)] ,						)




     def 		snake_case_		(				self ,						a__):
         A__		 =					input
         for layer in self.layers:
             A__		 =					layer(a__)
         return hidden_state







class     _UpperCAmelCase			(       nn.Module     ):




     def __init__(				self ,						a__):
         super().__init__()
         A__		 =					nn.ModuleList([])
         # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
         self.stages.append(
             ResNetStage(
                 a__ ,						config.embedding_size ,						config.hidden_sizes[0] ,						stride=2 if config.downsample_in_first_stage else 1 ,						depth=config.depths[0] ,						))
         A__		 =					zip(config.hidden_sizes ,						config.hidden_sizes[1:])
         for (in_channels, out_channels), depth in zip(a__ ,						config.depths[1:]):
             self.stages.append(ResNetStage(a__ ,						a__ ,						a__ ,						depth=a__))




     def 		snake_case_		(				self ,						a__ ,						a__ = False ,						a__ = True):
         A__		 =					() if output_hidden_states else None

         for stage_module in self.stages:
             if output_hidden_states:
                 A__		 =					hidden_states + (hidden_state,)

             A__		 =					stage_module(a__)

         if output_hidden_states:
             A__		 =					hidden_states + (hidden_state,)

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

         return BaseModelOutputWithNoAttention(
             last_hidden_state=a__ ,						hidden_states=a__ ,						)







class     _UpperCAmelCase			(       A__     ):
     UpperCamelCase__		    =				ResNetConfig
     UpperCamelCase__		    =				'''resnet'''
     UpperCamelCase__		    =				'''pixel_values'''
     UpperCamelCase__		    =				True




     def 		snake_case_		(				self ,						a__):
         if isinstance(a__ ,						nn.Convad):
             nn.init.kaiming_normal_(module.weight ,						mode='''fan_out''' ,						nonlinearity='''relu''')
         elif isinstance(a__ ,						(nn.BatchNormad, nn.GroupNorm)):
             nn.init.constant_(module.weight ,						1)
             nn.init.constant_(module.bias ,						0)




     def 		snake_case_		(				self ,						a__ ,						a__=False):
         if isinstance(a__ ,						a__):
             A__		 =					value







_lowercase						  =		R"\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n"

_lowercase						  =		R"\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`ConvNextImageProcessor.__call__`] for details.\n\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n"



@add_start_docstrings(
    '''The bare ResNet model outputting raw features without any specific head on top.'''			,      A__			,      )
class     _UpperCAmelCase			(       A__     ):




     def __init__(				self ,						a__):
         super().__init__(a__)
         A__		 =					config
         A__		 =					ResNetEmbeddings(a__)
         A__		 =					ResNetEncoder(a__)
         A__		 =					nn.AdaptiveAvgPoolad((1, 1))
         # Initialize weights and apply final processing
         self.post_init()




     @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 		snake_case_		(				self ,						a__ ,						a__ = None ,						a__ = None):
         A__		 =					(
             output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
         )
         A__		 =					return_dict if return_dict is not None else self.config.use_return_dict

         A__		 =					self.embedder(a__)

         A__		 =					self.encoder(
             a__ ,						output_hidden_states=a__ ,						return_dict=a__)

         A__		 =					encoder_outputs[0]

         A__		 =					self.pooler(a__)

         if not return_dict:
             return (last_hidden_state, pooled_output) + encoder_outputs[1:]

         return BaseModelOutputWithPoolingAndNoAttention(
             last_hidden_state=a__ ,						pooler_output=a__ ,						hidden_states=encoder_outputs.hidden_states ,						)







@add_start_docstrings(
    '''
    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    '''			,      A__			,      )
class     _UpperCAmelCase			(       A__     ):




     def __init__(				self ,						a__):
         super().__init__(a__)
         A__		 =					config.num_labels
         A__		 =					ResNetModel(a__)
         # classification head
         A__		 =					nn.Sequential(
             nn.Flatten() ,						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 		snake_case_		(				self ,						a__ = None ,						a__ = None ,						a__ = None ,						a__ = None ,						):
         A__		 =					return_dict if return_dict is not None else self.config.use_return_dict

         A__		 =					self.resnet(a__ ,						output_hidden_states=a__ ,						return_dict=a__)

         A__		 =					outputs.pooler_output if return_dict else outputs[1]

         A__		 =					self.classifier(a__)

         A__		 =					None

         if labels is not None:
             if self.config.problem_type is None:
                 if self.num_labels == 1:
                     A__		 =					'''regression'''
                 elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
                     A__		 =					'''single_label_classification'''
                 else:
                     A__		 =					'''multi_label_classification'''
             if self.config.problem_type == "regression":
                 A__		 =					MSELoss()
                 if self.num_labels == 1:
                     A__		 =					loss_fct(logits.squeeze() ,						labels.squeeze())
                 else:
                     A__		 =					loss_fct(a__ ,						a__)
             elif self.config.problem_type == "single_label_classification":
                 A__		 =					CrossEntropyLoss()
                 A__		 =					loss_fct(logits.view(-1 ,						self.num_labels) ,						labels.view(-1))
             elif self.config.problem_type == "multi_label_classification":
                 A__		 =					BCEWithLogitsLoss()
                 A__		 =					loss_fct(a__ ,						a__)

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

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







@add_start_docstrings(
    '''
    ResNet backbone, to be used with frameworks like DETR and MaskFormer.
    '''			,      A__			,      )
class     _UpperCAmelCase			(       A__			,      A__     ):




     def __init__(				self ,						a__):
         super().__init__(a__)
         super()._init_backbone(a__)

         A__		 =					[config.embedding_size] + config.hidden_sizes
         A__		 =					ResNetEmbeddings(a__)
         A__		 =					ResNetEncoder(a__)

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




     @add_start_docstrings_to_model_forward(a__)
     @replace_return_docstrings(output_type=a__ ,						config_class=_CONFIG_FOR_DOC)
     def 		snake_case_		(				self ,						a__ ,						a__ = None ,						a__ = None):
         A__		 =					return_dict if return_dict is not None else self.config.use_return_dict
         A__		 =					(
             output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
         )

         A__		 =					self.embedder(a__)

         A__		 =					self.encoder(a__ ,						output_hidden_states=a__ ,						return_dict=a__)

         A__		 =					outputs.hidden_states

         A__		 =					()
         for idx, stage in enumerate(self.stage_names):
             if stage in self.out_features:
                 feature_maps += (hidden_states[idx],)

         if not return_dict:
             A__		 =					(feature_maps,)
             if output_hidden_states:
                 output += (outputs.hidden_states,)
             return output

         return BackboneOutput(
             feature_maps=a__ ,						hidden_states=outputs.hidden_states if output_hidden_states else None ,						attentions=a__ ,						)





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     _UpperCAmelCase			(       A__			,      A__			,      unittest.TestCase     ):
     UpperCamelCase__		    =				IFPipeline
     UpperCamelCase__		    =				TEXT_TO_IMAGE_PARAMS - {'''width''', '''height''', '''latents'''}
     UpperCamelCase__		    =				TEXT_TO_IMAGE_BATCH_PARAMS
     UpperCamelCase__		    =				PipelineTesterMixin.required_optional_params - {'''latents'''}




     def 		snake_case_		(				self):
         return self._get_dummy_components()




     def 		snake_case_		(				self ,						a__ ,						a__=0):
         if str(a__).startswith('''mps'''):
             A__		 =					torch.manual_seed(a__)
         else:
             A__		 =					torch.Generator(device=a__).manual_seed(a__)

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

         return inputs




     def 		snake_case_		(				self):
         self._test_save_load_optional_components()




     @unittest.skipIf(torch_device != '''cuda''' ,						reason='''float16 requires CUDA''')
     def 		snake_case_		(				self):
         # 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 		snake_case_		(				self):
         self._test_attention_slicing_forward_pass(expected_max_diff=1e-2)




     def 		snake_case_		(				self):
         self._test_save_load_local()




     def 		snake_case_		(				self):
         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 		snake_case_		(				self):
         self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3)







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




     def 		snake_case_		(				self):
         # clean up the VRAM after each test
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()




     def 		snake_case_		(				self):
         # if

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

         A__		 =					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''')

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

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

         A__		 =					None
         A__		 =					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

         A__		 =					IFImgaImgPipeline(**pipe_a.components)
         A__		 =					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

         A__		 =					IFInpaintingPipeline(**pipe_a.components)
         A__		 =					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 		snake_case_		(				self ,						a__ ,						a__ ,						a__ ,						a__):
         # pipeline 1

         _start_torch_memory_measurement()

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

         A__		 =					output.images[0]

         assert image.shape == (6_4, 6_4, 3)

         A__		 =					torch.cuda.max_memory_allocated()
         assert mem_bytes < 1_3 * 1_0**9

         A__		 =					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()

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

         A__		 =					floats_tensor((1, 3, 6_4, 6_4) ,						rng=random.Random(0)).to(a__)

         A__		 =					pipe_a(
             prompt_embeds=a__ ,						negative_prompt_embeds=a__ ,						image=a__ ,						generator=a__ ,						num_inference_steps=2 ,						output_type='''np''' ,						)

         A__		 =					output.images[0]

         assert image.shape == (2_5_6, 2_5_6, 3)

         A__		 =					torch.cuda.max_memory_allocated()
         assert mem_bytes < 4 * 1_0**9

         A__		 =					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 		snake_case_		(				self ,						a__ ,						a__ ,						a__ ,						a__):
         # pipeline 1

         _start_torch_memory_measurement()

         A__		 =					floats_tensor((1, 3, 6_4, 6_4) ,						rng=random.Random(0)).to(a__)

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

         A__		 =					pipe_a(
             prompt_embeds=a__ ,						negative_prompt_embeds=a__ ,						image=a__ ,						num_inference_steps=2 ,						generator=a__ ,						output_type='''np''' ,						)

         A__		 =					output.images[0]

         assert image.shape == (6_4, 6_4, 3)

         A__		 =					torch.cuda.max_memory_allocated()
         assert mem_bytes < 1_0 * 1_0**9

         A__		 =					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()

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

         A__		 =					floats_tensor((1, 3, 2_5_6, 2_5_6) ,						rng=random.Random(0)).to(a__)
         A__		 =					floats_tensor((1, 3, 6_4, 6_4) ,						rng=random.Random(0)).to(a__)

         A__		 =					pipe_a(
             prompt_embeds=a__ ,						negative_prompt_embeds=a__ ,						image=a__ ,						original_image=a__ ,						generator=a__ ,						num_inference_steps=2 ,						output_type='''np''' ,						)

         A__		 =					output.images[0]

         assert image.shape == (2_5_6, 2_5_6, 3)

         A__		 =					torch.cuda.max_memory_allocated()
         assert mem_bytes < 4 * 1_0**9

         A__		 =					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 		snake_case_		(				self ,						a__ ,						a__ ,						a__ ,						a__):
         # pipeline 1

         _start_torch_memory_measurement()

         A__		 =					floats_tensor((1, 3, 6_4, 6_4) ,						rng=random.Random(0)).to(a__)
         A__		 =					floats_tensor((1, 3, 6_4, 6_4) ,						rng=random.Random(1)).to(a__)

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

         A__		 =					output.images[0]

         assert image.shape == (6_4, 6_4, 3)

         A__		 =					torch.cuda.max_memory_allocated()
         assert mem_bytes < 1_0 * 1_0**9

         A__		 =					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()

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

         A__		 =					floats_tensor((1, 3, 6_4, 6_4) ,						rng=random.Random(0)).to(a__)
         A__		 =					floats_tensor((1, 3, 2_5_6, 2_5_6) ,						rng=random.Random(0)).to(a__)
         A__		 =					floats_tensor((1, 3, 2_5_6, 2_5_6) ,						rng=random.Random(1)).to(a__)

         A__		 =					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''' ,						)

         A__		 =					output.images[0]

         assert image.shape == (2_5_6, 2_5_6, 3)

         A__		 =					torch.cuda.max_memory_allocated()
         assert mem_bytes < 4 * 1_0**9

         A__		 =					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 		lowerCAmelCase__    (					)->  List[Any]:
    torch.cuda.empty_cache()
    torch.cuda.reset_max_memory_allocated()
    torch.cuda.reset_peak_memory_stats()
