





"""simple docstring"""




from typing import Optional, Union

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

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, 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_mobilenet_va import MobileNetVaConfig


a		:				Dict  			=    logging.get_logger(__name__)


# General docstring
a		:				Optional[Any]  			=    '''MobileNetV1Config'''

# Base docstring
a		:				Tuple  			=    '''google/mobilenet_v1_1.0_224'''
a		:				Dict  			=    [1, 1024, 7, 7]

# Image classification docstring
a		:				str  			=    '''google/mobilenet_v1_1.0_224'''
a		:				Any  			=    '''tabby, tabby cat'''


a		:				List[Any]  			=    [
    '''google/mobilenet_v1_1.0_224''',
    '''google/mobilenet_v1_0.75_192''',
    # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
]






def    _SCREAMING_SNAKE_CASE	(			_lowercase		:					List[Any]					, _lowercase		:					Optional[Any]					, _lowercase		:					Dict=None      )				->int:






	'''simple docstring'''






	a   :	Union[str, Any]			=       {}

	if isinstance(_lowercase					, _lowercase      ):
		a   :	List[Any]			=       model.mobilenet_va
	else:
		a   :	List[str]			=       model

	a   :	int			=       "MobilenetV1/Conv2d_0/"
	a   :	str			=       backbone.conv_stem.convolution.weight
	a   :	int			=       backbone.conv_stem.normalization.bias
	a   :	Optional[int]			=       backbone.conv_stem.normalization.weight
	a   :	List[Any]			=       backbone.conv_stem.normalization.running_mean
	a   :	List[str]			=       backbone.conv_stem.normalization.running_var

	for i in range(13      ):
		a   :	Dict			=       i + 1
		a   :	Union[str, Any]			=       i * 2

		a   :	Union[str, Any]			=       backbone.layer[pt_index]
		a   :	Optional[int]			=       F"""MobilenetV1/Conv2d_{tf_index}_depthwise/"""
		a   :	str			=       pointer.convolution.weight
		a   :	str			=       pointer.normalization.bias
		a   :	Optional[Any]			=       pointer.normalization.weight
		a   :	List[str]			=       pointer.normalization.running_mean
		a   :	Optional[int]			=       pointer.normalization.running_var

		a   :	str			=       backbone.layer[pt_index + 1]
		a   :	List[str]			=       F"""MobilenetV1/Conv2d_{tf_index}_pointwise/"""
		a   :	Tuple			=       pointer.convolution.weight
		a   :	Tuple			=       pointer.normalization.bias
		a   :	int			=       pointer.normalization.weight
		a   :	Dict			=       pointer.normalization.running_mean
		a   :	List[Any]			=       pointer.normalization.running_var

	if isinstance(_lowercase					, _lowercase      ):
		a   :	List[Any]			=       "MobilenetV1/Logits/Conv2d_1c_1x1/"
		a   :	int			=       model.classifier.weight
		a   :	Dict			=       model.classifier.bias

	return tf_to_pt_map






def    _SCREAMING_SNAKE_CASE	(			_lowercase		:					str					, _lowercase		:					int					, _lowercase		:					Tuple      )				->List[Any]:






	'''simple docstring'''






	try:
		import numpy as np
		import tensorflow as tf
	except ImportError:
		logger.error(
		    "Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see "
		    "https://www.tensorflow.org/install/ for installation instructions."      )
		raise

	# Load weights from TF model
	a   :	Any			=       tf.train.list_variables(_lowercase      )
	a   :	Tuple			=       {}
	for name, shape in init_vars:
		logger.info(F"""Loading TF weight {name} with shape {shape}"""      )
		a   :	int			=       tf.train.load_variable(_lowercase					, _lowercase      )
		a   :	Union[str, Any]			=       array

	# Build TF to PyTorch weights loading map
	a   :	List[str]			=       _build_tf_to_pytorch_map(_lowercase					, _lowercase					, _lowercase      )

	for name, pointer in tf_to_pt_map.items():
		logger.info(F"""Importing {name}"""      )
		if name not in tf_weights:
			logger.info(F"""{name} not in tf pre-trained weights, skipping"""      )
			continue

		a   :	int			=       tf_weights[name]

		if "depthwise_weights" in name:
			logger.info("Transposing depthwise"      )
			a   :	List[Any]			=       np.transpose(_lowercase					, (2, 3, 0, 1)      )
		elif "weights" in name:
			logger.info("Transposing"      )
			if len(pointer.shape      ) == 2:  # copying into linear layer
				a   :	List[str]			=       array.squeeze().transpose()
			else:
				a   :	Dict			=       np.transpose(_lowercase					, (3, 2, 0, 1)      )

		if pointer.shape != array.shape:
			raise ValueError(F"""Pointer shape {pointer.shape} and array shape {array.shape} mismatched"""      )

		logger.info(F"""Initialize PyTorch weight {name} {array.shape}"""      )
		a   :	List[Any]			=       torch.from_numpy(_lowercase      )

		tf_weights.pop(_lowercase					, _lowercase      )
		tf_weights.pop(name + "/RMSProp"					, _lowercase      )
		tf_weights.pop(name + "/RMSProp_1"					, _lowercase      )
		tf_weights.pop(name + "/ExponentialMovingAverage"					, _lowercase      )

	logger.info(F"""Weights not copied to PyTorch model: {', '.join(tf_weights.keys()      )}"""      )
	return model






def    _SCREAMING_SNAKE_CASE	(			_lowercase		:					torch.Tensor					, _lowercase		:					nn.Convad      )				->torch.Tensor:






	'''simple docstring'''






	a, a   :	Tuple			=       features.shape[-2:]
	a, a   :	List[Any]			=       conv_layer.stride
	a, a   :	Any			=       conv_layer.kernel_size

	if in_height % stride_height == 0:
		a   :	Union[str, Any]			=       max(kernel_height - stride_height					, 0      )
	else:
		a   :	int			=       max(kernel_height - (in_height % stride_height)					, 0      )

	if in_width % stride_width == 0:
		a   :	Union[str, Any]			=       max(kernel_width - stride_width					, 0      )
	else:
		a   :	Optional[Any]			=       max(kernel_width - (in_width % stride_width)					, 0      )

	a   :	Tuple			=       pad_along_width // 2
	a   :	Union[str, Any]			=       pad_along_width - pad_left
	a   :	str			=       pad_along_height // 2
	a   :	Tuple			=       pad_along_height - pad_top

	a   :	Any			=       (pad_left, pad_right, pad_top, pad_bottom)
	return nn.functional.pad(_lowercase					, _lowercase					, "constant"					, 0.0      )


class  __UpperCamelCase       (		nn.Module		):






							def __init__(     self   ,      lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__ = 1   ,      lowerCAmelCase__ = 1   ,      lowerCAmelCase__ = False   ,      lowerCAmelCase__ = True   ,      lowerCAmelCase__ = True   ,      )			->				None:
								super().__init__()
								a   :	str			=       config

								if in_channels % groups != 0:
									raise ValueError(f"""Input channels ({in_channels}) are not divisible by {groups} groups."""   )
								if out_channels % groups != 0:
									raise ValueError(f"""Output channels ({out_channels}) are not divisible by {groups} groups."""   )

								a   :	List[str]			=       0 if config.tf_padding else int((kernel_size - 1) / 2   )

								a   :	List[Any]			=       nn.Convad(
								    in_channels=lowerCAmelCase__   ,      out_channels=lowerCAmelCase__   ,      kernel_size=lowerCAmelCase__   ,      stride=lowerCAmelCase__   ,      padding=lowerCAmelCase__   ,      groups=lowerCAmelCase__   ,      bias=lowerCAmelCase__   ,      padding_mode="zeros"   ,      )

								if use_normalization:
									a   :	Optional[int]			=       nn.BatchNormad(
									    num_features=lowerCAmelCase__   ,      eps=config.layer_norm_eps   ,      momentum=0.9_997   ,      affine=lowerCAmelCase__   ,      track_running_stats=lowerCAmelCase__   ,      )
								else:
									a   :	List[str]			=       None

								if use_activation:
									if isinstance(lowerCAmelCase__   ,      lowerCAmelCase__   ):
										a   :	Any			=       ACTaFN[use_activation]
									elif isinstance(config.hidden_act   ,      lowerCAmelCase__   ):
										a   :	Optional[Any]			=       ACTaFN[config.hidden_act]
									else:
										a   :	Any			=       config.hidden_act
								else:
									a   :	Tuple			=       None






							def 					__a     (     self   ,      lowerCAmelCase__   )			->				torch.Tensor:
								if self.config.tf_padding:
									a   :	str			=       apply_tf_padding(lowerCAmelCase__   ,      self.convolution   )
								a   :	Any			=       self.convolution(lowerCAmelCase__   )
								if self.normalization is not None:
									a   :	str			=       self.normalization(lowerCAmelCase__   )
								if self.activation is not None:
									a   :	Any			=       self.activation(lowerCAmelCase__   )
								return features


class  __UpperCamelCase       (		a__		):
							lowerCamelCase     :      Any         =MobileNetVaConfig
							lowerCamelCase     :      Any         =load_tf_weights_in_mobilenet_va
							lowerCamelCase     :      Tuple         ="""mobilenet_v1"""
							lowerCamelCase     :      List[Any]         ="""pixel_values"""
							lowerCamelCase     :      List[str]         =False






							def 					__a     (     self   ,      lowerCAmelCase__   )			->				None:
								if isinstance(lowerCAmelCase__   ,      (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(lowerCAmelCase__   ,      nn.BatchNormad   ):
									module.bias.data.zero_()
									module.weight.data.fill_(1.0   )
a		:				Any  			=    R'''
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`MobileNetV1Config`]): 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.
'''

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


@add_start_docstrings(
    """The bare MobileNetV1 model outputting raw hidden-states without any specific head on top."""	, a__	, )
class  __UpperCamelCase       (		a__		):






							def __init__(     self   ,      lowerCAmelCase__   ,      lowerCAmelCase__ = True   )			->				int:
								super().__init__(lowerCAmelCase__   )
								a   :	Any			=       config

								a   :	Tuple			=       32
								a   :	Union[str, Any]			=       max(int(depth * config.depth_multiplier   )   ,      config.min_depth   )

								a   :	Optional[Any]			=       MobileNetVaConvLayer(
								    lowerCAmelCase__   ,      in_channels=config.num_channels   ,      out_channels=lowerCAmelCase__   ,      kernel_size=3   ,      stride=2   ,      )

								a   :	Optional[int]			=       [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

								a   :	List[str]			=       nn.ModuleList()
								for i in range(13   ):
									a   :	Union[str, Any]			=       out_channels

									if strides[i] == 2 or i == 0:
										depth *= 2
										a   :	int			=       max(int(depth * config.depth_multiplier   )   ,      config.min_depth   )

									self.layer.append(
									    MobileNetVaConvLayer(
									        lowerCAmelCase__   ,      in_channels=lowerCAmelCase__   ,      out_channels=lowerCAmelCase__   ,      kernel_size=3   ,      stride=strides[i]   ,      groups=lowerCAmelCase__   ,      )   )

									self.layer.append(
									    MobileNetVaConvLayer(
									        lowerCAmelCase__   ,      in_channels=lowerCAmelCase__   ,      out_channels=lowerCAmelCase__   ,      kernel_size=1   ,      )   )

								a   :	Any			=       nn.AdaptiveAvgPoolad((1, 1)   ) if add_pooling_layer else None

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






							def 					__a     (     self   ,      lowerCAmelCase__   )			->				str:
								raise NotImplementedError






							@add_start_docstrings_to_model_forward(lowerCAmelCase__   )
							@add_code_sample_docstrings(
							    checkpoint=_CHECKPOINT_FOR_DOC   ,      output_type=lowerCAmelCase__   ,      config_class=_CONFIG_FOR_DOC   ,      modality="vision"   ,      expected_output=_EXPECTED_OUTPUT_SHAPE   ,      )
							def 					__a     (     self   ,      lowerCAmelCase__ = None   ,      lowerCAmelCase__ = None   ,      lowerCAmelCase__ = None   ,      )			->				Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:
								a   :	Optional[Any]			=       (
								    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
								)
								a   :	List[Any]			=       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"   )

								a   :	str			=       self.conv_stem(lowerCAmelCase__   )

								a   :	Tuple			=       () if output_hidden_states else None

								for i, layer_module in enumerate(self.layer   ):
									a   :	Optional[int]			=       layer_module(lowerCAmelCase__   )

									if output_hidden_states:
										a   :	List[str]			=       all_hidden_states + (hidden_states,)

								a   :	List[Any]			=       hidden_states

								if self.pooler is not None:
									a   :	str			=       torch.flatten(self.pooler(lowerCAmelCase__   )   ,      start_dim=1   )
								else:
									a   :	str			=       None

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

								return BaseModelOutputWithPoolingAndNoAttention(
								    last_hidden_state=lowerCAmelCase__   ,      pooler_output=lowerCAmelCase__   ,      hidden_states=lowerCAmelCase__   ,      )


@add_start_docstrings(
    """
    MobileNetV1 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   ,      lowerCAmelCase__   )			->				None:
								super().__init__(lowerCAmelCase__   )

								a   :	Tuple			=       config.num_labels
								a   :	Optional[Any]			=       MobileNetVaModel(lowerCAmelCase__   )

								a   :	List[Any]			=       self.mobilenet_va.layer[-1].convolution.out_channels

								# Classifier head
								a   :	str			=       nn.Dropout(config.classifier_dropout_prob   ,      inplace=lowerCAmelCase__   )
								a   :	int			=       nn.Linear(lowerCAmelCase__   ,      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(lowerCAmelCase__   )
							@add_code_sample_docstrings(
							    checkpoint=_IMAGE_CLASS_CHECKPOINT   ,      output_type=lowerCAmelCase__   ,      config_class=_CONFIG_FOR_DOC   ,      expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT   ,      )
							def 					__a     (     self   ,      lowerCAmelCase__ = None   ,      lowerCAmelCase__ = None   ,      lowerCAmelCase__ = None   ,      lowerCAmelCase__ = None   ,      )			->				Union[tuple, ImageClassifierOutputWithNoAttention]:
								a   :	Tuple			=       return_dict if return_dict is not None else self.config.use_return_dict

								a   :	Dict			=       self.mobilenet_va(lowerCAmelCase__   ,      output_hidden_states=lowerCAmelCase__   ,      return_dict=lowerCAmelCase__   )

								a   :	Tuple			=       outputs.pooler_output if return_dict else outputs[1]

								a   :	Optional[int]			=       self.classifier(self.dropout(lowerCAmelCase__   )   )

								a   :	Optional[Any]			=       None
								if labels is not None:
									if self.config.problem_type is None:
										if self.num_labels == 1:
											a   :	List[Any]			=       "regression"
										elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
											a   :	Optional[Any]			=       "single_label_classification"
										else:
											a   :	Optional[int]			=       "multi_label_classification"

									if self.config.problem_type == "regression":
										a   :	Any			=       MSELoss()
										if self.num_labels == 1:
											a   :	Optional[Any]			=       loss_fct(logits.squeeze()   ,      labels.squeeze()   )
										else:
											a   :	Dict			=       loss_fct(lowerCAmelCase__   ,      lowerCAmelCase__   )
									elif self.config.problem_type == "single_label_classification":
										a   :	Any			=       CrossEntropyLoss()
										a   :	str			=       loss_fct(logits.view(-1   ,      self.num_labels   )   ,      labels.view(-1   )   )
									elif self.config.problem_type == "multi_label_classification":
										a   :	Union[str, Any]			=       BCEWithLogitsLoss()
										a   :	Optional[Any]			=       loss_fct(lowerCAmelCase__   ,      lowerCAmelCase__   )

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

								return ImageClassifierOutputWithNoAttention(
								    loss=lowerCAmelCase__   ,      logits=lowerCAmelCase__   ,      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  __UpperCamelCase       (		a__	, a__	, unittest.TestCase		):
							lowerCamelCase     :      Dict         =IFPipeline
							lowerCamelCase     :      int         =TEXT_TO_IMAGE_PARAMS - {"""width""", """height""", """latents"""}
							lowerCamelCase     :      int         =TEXT_TO_IMAGE_BATCH_PARAMS
							lowerCamelCase     :      int         =PipelineTesterMixin.required_optional_params - {"""latents"""}






							def 					__a     (     self   )			->				List[str]:
								return self._get_dummy_components()






							def 					__a     (     self   ,      lowerCAmelCase__   ,      lowerCAmelCase__=0   )			->				Dict:
								if str(lowerCAmelCase__   ).startswith("mps"   ):
									a   :	Tuple			=       torch.manual_seed(lowerCAmelCase__   )
								else:
									a   :	int			=       torch.Generator(device=lowerCAmelCase__   ).manual_seed(lowerCAmelCase__   )

								a   :	Optional[Any]			=       {
								    "prompt": "A painting of a squirrel eating a burger",
								    "generator": generator,
								    "num_inference_steps": 2,
								    "output_type": "numpy",
								}

								return inputs






							def 					__a     (     self   )			->				Union[str, Any]:
								self._test_save_load_optional_components()






							@unittest.skipIf(torch_device != "cuda"   ,      reason="float16 requires CUDA"   )
							def 					__a     (     self   )			->				Any:
								# 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 					__a     (     self   )			->				Union[str, Any]:
								self._test_attention_slicing_forward_pass(expected_max_diff=1E-2   )






							def 					__a     (     self   )			->				Optional[int]:
								self._test_save_load_local()






							def 					__a     (     self   )			->				Tuple:
								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 					__a     (     self   )			->				str:
								self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3   )


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






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






							def 					__a     (     self   )			->				Tuple:
								# if

								a   :	Tuple			=       IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0"   ,      variant="fp16"   ,      torch_dtype=torch.floataa   )

								a   :	str			=       IFSuperResolutionPipeline.from_pretrained(
								    "DeepFloyd/IF-II-L-v1.0"   ,      variant="fp16"   ,      torch_dtype=torch.floataa   ,      text_encoder=lowerCAmelCase__   ,      tokenizer=lowerCAmelCase__   )

								# pre compute text embeddings and remove T5 to save memory

								pipe_a.text_encoder.to("cuda"   )

								a, a   :	List[str]			=       pipe_a.encode_prompt("anime turtle"   ,      device="cuda"   )

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

								a   :	Optional[int]			=       None
								a   :	Optional[int]			=       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(lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   )

								pipe_a.remove_all_hooks()
								pipe_a.remove_all_hooks()

								# img2img

								a   :	Union[str, Any]			=       IFImgaImgPipeline(**pipe_a.components   )
								a   :	List[Any]			=       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(lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   )

								pipe_a.remove_all_hooks()
								pipe_a.remove_all_hooks()

								# inpainting

								a   :	Union[str, Any]			=       IFInpaintingPipeline(**pipe_a.components   )
								a   :	List[str]			=       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(lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   )






							def 					__a     (     self   ,      lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   )			->				Dict:
								# pipeline 1

								_start_torch_memory_measurement()

								a   :	List[str]			=       torch.Generator(device="cpu"   ).manual_seed(0   )
								a   :	Dict			=       pipe_a(
								    prompt_embeds=lowerCAmelCase__   ,      negative_prompt_embeds=lowerCAmelCase__   ,      num_inference_steps=2   ,      generator=lowerCAmelCase__   ,      output_type="np"   ,      )

								a   :	List[str]			=       output.images[0]

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

								a   :	Dict			=       torch.cuda.max_memory_allocated()
								assert mem_bytes < 13 * 10**9

								a   :	Optional[Any]			=       load_numpy(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy"   )
								assert_mean_pixel_difference(lowerCAmelCase__   ,      lowerCAmelCase__   )

								# pipeline 2

								_start_torch_memory_measurement()

								a   :	List[str]			=       torch.Generator(device="cpu"   ).manual_seed(0   )

								a   :	Optional[int]			=       floats_tensor((1, 3, 64, 64)   ,      rng=random.Random(0   )   ).to(lowerCAmelCase__   )

								a   :	Union[str, Any]			=       pipe_a(
								    prompt_embeds=lowerCAmelCase__   ,      negative_prompt_embeds=lowerCAmelCase__   ,      image=lowerCAmelCase__   ,      generator=lowerCAmelCase__   ,      num_inference_steps=2   ,      output_type="np"   ,      )

								a   :	List[str]			=       output.images[0]

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

								a   :	int			=       torch.cuda.max_memory_allocated()
								assert mem_bytes < 4 * 10**9

								a   :	Union[str, Any]			=       load_numpy(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy"   )
								assert_mean_pixel_difference(lowerCAmelCase__   ,      lowerCAmelCase__   )






							def 					__a     (     self   ,      lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   )			->				int:
								# pipeline 1

								_start_torch_memory_measurement()

								a   :	int			=       floats_tensor((1, 3, 64, 64)   ,      rng=random.Random(0   )   ).to(lowerCAmelCase__   )

								a   :	Tuple			=       torch.Generator(device="cpu"   ).manual_seed(0   )

								a   :	List[Any]			=       pipe_a(
								    prompt_embeds=lowerCAmelCase__   ,      negative_prompt_embeds=lowerCAmelCase__   ,      image=lowerCAmelCase__   ,      num_inference_steps=2   ,      generator=lowerCAmelCase__   ,      output_type="np"   ,      )

								a   :	Tuple			=       output.images[0]

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

								a   :	int			=       torch.cuda.max_memory_allocated()
								assert mem_bytes < 10 * 10**9

								a   :	Optional[int]			=       load_numpy(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy"   )
								assert_mean_pixel_difference(lowerCAmelCase__   ,      lowerCAmelCase__   )

								# pipeline 2

								_start_torch_memory_measurement()

								a   :	Optional[int]			=       torch.Generator(device="cpu"   ).manual_seed(0   )

								a   :	List[Any]			=       floats_tensor((1, 3, 256, 256)   ,      rng=random.Random(0   )   ).to(lowerCAmelCase__   )
								a   :	str			=       floats_tensor((1, 3, 64, 64)   ,      rng=random.Random(0   )   ).to(lowerCAmelCase__   )

								a   :	Dict			=       pipe_a(
								    prompt_embeds=lowerCAmelCase__   ,      negative_prompt_embeds=lowerCAmelCase__   ,      image=lowerCAmelCase__   ,      original_image=lowerCAmelCase__   ,      generator=lowerCAmelCase__   ,      num_inference_steps=2   ,      output_type="np"   ,      )

								a   :	int			=       output.images[0]

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

								a   :	str			=       torch.cuda.max_memory_allocated()
								assert mem_bytes < 4 * 10**9

								a   :	Any			=       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(lowerCAmelCase__   ,      lowerCAmelCase__   )






							def 					__a     (     self   ,      lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   )			->				Optional[int]:
								# pipeline 1

								_start_torch_memory_measurement()

								a   :	Union[str, Any]			=       floats_tensor((1, 3, 64, 64)   ,      rng=random.Random(0   )   ).to(lowerCAmelCase__   )
								a   :	List[Any]			=       floats_tensor((1, 3, 64, 64)   ,      rng=random.Random(1   )   ).to(lowerCAmelCase__   )

								a   :	Optional[int]			=       torch.Generator(device="cpu"   ).manual_seed(0   )
								a   :	List[str]			=       pipe_a(
								    prompt_embeds=lowerCAmelCase__   ,      negative_prompt_embeds=lowerCAmelCase__   ,      image=lowerCAmelCase__   ,      mask_image=lowerCAmelCase__   ,      num_inference_steps=2   ,      generator=lowerCAmelCase__   ,      output_type="np"   ,      )

								a   :	List[Any]			=       output.images[0]

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

								a   :	Tuple			=       torch.cuda.max_memory_allocated()
								assert mem_bytes < 10 * 10**9

								a   :	Union[str, Any]			=       load_numpy(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy"   )
								assert_mean_pixel_difference(lowerCAmelCase__   ,      lowerCAmelCase__   )

								# pipeline 2

								_start_torch_memory_measurement()

								a   :	str			=       torch.Generator(device="cpu"   ).manual_seed(0   )

								a   :	Optional[int]			=       floats_tensor((1, 3, 64, 64)   ,      rng=random.Random(0   )   ).to(lowerCAmelCase__   )
								a   :	int			=       floats_tensor((1, 3, 256, 256)   ,      rng=random.Random(0   )   ).to(lowerCAmelCase__   )
								a   :	Dict			=       floats_tensor((1, 3, 256, 256)   ,      rng=random.Random(1   )   ).to(lowerCAmelCase__   )

								a   :	Optional[int]			=       pipe_a(
								    prompt_embeds=lowerCAmelCase__   ,      negative_prompt_embeds=lowerCAmelCase__   ,      image=lowerCAmelCase__   ,      mask_image=lowerCAmelCase__   ,      original_image=lowerCAmelCase__   ,      generator=lowerCAmelCase__   ,      num_inference_steps=2   ,      output_type="np"   ,      )

								a   :	List[str]			=       output.images[0]

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

								a   :	Tuple			=       torch.cuda.max_memory_allocated()
								assert mem_bytes < 4 * 10**9

								a   :	Optional[Any]			=       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(lowerCAmelCase__   ,      lowerCAmelCase__   )






def    _SCREAMING_SNAKE_CASE	(			)				->List[str]:






	'''simple docstring'''






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


