
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				=logging.get_logger(__name__)


# General docstring
__A				='''MobileNetV1Config'''

# Base docstring
__A				='''google/mobilenet_v1_1.0_224'''
__A				=[1, 1_0_2_4, 7, 7]

# Image classification docstring
__A				='''google/mobilenet_v1_1.0_224'''
__A				='''tabby, tabby cat'''


__A				=[
    '''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 			lowerCamelCase_ (				lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__=None    ):
				lowerCamelCase_						=			{}

				if isinstance(lowerCamelCase__	, lowerCamelCase__    ):
								lowerCamelCase_						=			model.mobilenet_va
				else:
								lowerCamelCase_						=			model

				lowerCamelCase_						=			"MobilenetV1/Conv2d_0/"
				lowerCamelCase_						=			backbone.conv_stem.convolution.weight
				lowerCamelCase_						=			backbone.conv_stem.normalization.bias
				lowerCamelCase_						=			backbone.conv_stem.normalization.weight
				lowerCamelCase_						=			backbone.conv_stem.normalization.running_mean
				lowerCamelCase_						=			backbone.conv_stem.normalization.running_var

				for i in range(1_3    ):
								lowerCamelCase_						=			i + 1
								lowerCamelCase_						=			i * 2

								lowerCamelCase_						=			backbone.layer[pt_index]
								lowerCamelCase_						=			F'MobilenetV1/Conv2d_{tf_index}_depthwise/'
								lowerCamelCase_						=			pointer.convolution.weight
								lowerCamelCase_						=			pointer.normalization.bias
								lowerCamelCase_						=			pointer.normalization.weight
								lowerCamelCase_						=			pointer.normalization.running_mean
								lowerCamelCase_						=			pointer.normalization.running_var

								lowerCamelCase_						=			backbone.layer[pt_index + 1]
								lowerCamelCase_						=			F'MobilenetV1/Conv2d_{tf_index}_pointwise/'
								lowerCamelCase_						=			pointer.convolution.weight
								lowerCamelCase_						=			pointer.normalization.bias
								lowerCamelCase_						=			pointer.normalization.weight
								lowerCamelCase_						=			pointer.normalization.running_mean
								lowerCamelCase_						=			pointer.normalization.running_var

				if isinstance(lowerCamelCase__	, lowerCamelCase__    ):
								lowerCamelCase_						=			"MobilenetV1/Logits/Conv2d_1c_1x1/"
								lowerCamelCase_						=			model.classifier.weight
								lowerCamelCase_						=			model.classifier.bias

				return tf_to_pt_map





def 			lowerCamelCase_ (				lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__    ):
				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
				lowerCamelCase_						=			tf.train.list_variables(lowerCamelCase__    )
				lowerCamelCase_						=			{}
				for name, shape in init_vars:
								logger.info(F'Loading TF weight {name} with shape {shape}'    )
								lowerCamelCase_						=			tf.train.load_variable(lowerCamelCase__	, lowerCamelCase__    )
								lowerCamelCase_						=			array

				# Build TF to PyTorch weights loading map
				lowerCamelCase_						=			_build_tf_to_pytorch_map(lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__    )

				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

								lowerCamelCase_						=			tf_weights[name]

								if "depthwise_weights" in name:
												logger.info("Transposing depthwise"    )
												lowerCamelCase_						=			np.transpose(lowerCamelCase__	, (2, 3, 0, 1)    )
								elif "weights" in name:
												logger.info("Transposing"    )
												if len(pointer.shape    ) == 2:  # copying into linear layer
																lowerCamelCase_						=			array.squeeze().transpose()
												else:
																lowerCamelCase_						=			np.transpose(lowerCamelCase__	, (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}'    )
								lowerCamelCase_						=			torch.from_numpy(lowerCamelCase__    )

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

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





def 			lowerCamelCase_ (				lowerCamelCase__	, lowerCamelCase__    ):
				lowerCamelCase_	,    lowerCamelCase_						=			features.shape[-2:]
				lowerCamelCase_	,    lowerCamelCase_						=			conv_layer.stride
				lowerCamelCase_	,    lowerCamelCase_						=			conv_layer.kernel_size

				if in_height % stride_height == 0:
								lowerCamelCase_						=			max(kernel_height - stride_height	, 0    )
				else:
								lowerCamelCase_						=			max(kernel_height - (in_height % stride_height)	, 0    )

				if in_width % stride_width == 0:
								lowerCamelCase_						=			max(kernel_width - stride_width	, 0    )
				else:
								lowerCamelCase_						=			max(kernel_width - (in_width % stride_width)	, 0    )

				lowerCamelCase_						=			pad_along_width // 2
				lowerCamelCase_						=			pad_along_width - pad_left
				lowerCamelCase_						=			pad_along_height // 2
				lowerCamelCase_						=			pad_along_height - pad_top

				lowerCamelCase_						=			(pad_left, pad_right, pad_top, pad_bottom)
				return nn.functional.pad(lowerCamelCase__	, lowerCamelCase__	, "constant"	, 0.0    )




class     _SCREAMING_SNAKE_CASE     (      nn.Module						):



	def __init__(    self						,  lowercase						,  lowercase						,  lowercase						,  lowercase						,  lowercase = 1						,  lowercase = 1						,  lowercase = False						,  lowercase = True						,  lowercase = True						,  )				->       None:
					super().__init__()
					lowerCamelCase_						=			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.' )

					lowerCamelCase_						=			0 if config.tf_padding else int((kernel_size - 1) / 2 )

					lowerCamelCase_						=			nn.Convad(
					    in_channels=lowercase						,  out_channels=lowercase						,  kernel_size=lowercase						,  stride=lowercase						,  padding=lowercase						,  groups=lowercase						,  bias=lowercase						,  padding_mode="zeros"						,  )

					if use_normalization:
									lowerCamelCase_						=			nn.BatchNormad(
									    num_features=lowercase						,  eps=config.layer_norm_eps						,  momentum=0.9_9_9_7						,  affine=lowercase						,  track_running_stats=lowercase						,  )
					else:
									lowerCamelCase_						=			None

					if use_activation:
									if isinstance(lowercase						,  lowercase ):
													lowerCamelCase_						=			ACTaFN[use_activation]
									elif isinstance(config.hidden_act						,  lowercase ):
													lowerCamelCase_						=			ACTaFN[config.hidden_act]
									else:
													lowerCamelCase_						=			config.hidden_act
					else:
									lowerCamelCase_						=			None



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase )				->       torch.Tensor:
					if self.config.tf_padding:
									lowerCamelCase_						=			apply_tf_padding(lowercase						,  self.convolution )
					lowerCamelCase_						=			self.convolution(lowercase )
					if self.normalization is not None:
									lowerCamelCase_						=			self.normalization(lowercase )
					if self.activation is not None:
									lowerCamelCase_						=			self.activation(lowercase )
					return features




class     _SCREAMING_SNAKE_CASE     (      snake_case_						):
	lowerCAmelCase__         = MobileNetVaConfig
	lowerCAmelCase__         = load_tf_weights_in_mobilenet_va
	lowerCAmelCase__         = 'mobilenet_v1'
	lowerCAmelCase__         = 'pixel_values'
	lowerCAmelCase__         = False



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase )				->       None:
					if isinstance(lowercase						,  (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(lowercase						,  nn.BatchNormad ):
									module.bias.data.zero_()
									module.weight.data.fill_(1.0 )



__A				=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				=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.'			,       snake_case_			,       )
class     _SCREAMING_SNAKE_CASE     (      snake_case_						):



	def __init__(    self						,  lowercase						,  lowercase = True )				->       Optional[Any]:
					super().__init__(lowercase )
					lowerCamelCase_						=			config

					lowerCamelCase_						=			32
					lowerCamelCase_						=			max(int(depth * config.depth_multiplier )						,  config.min_depth )

					lowerCamelCase_						=			MobileNetVaConvLayer(
					    lowercase						,  in_channels=config.num_channels						,  out_channels=lowercase						,  kernel_size=3						,  stride=2						,  )

					lowerCamelCase_						=			[1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

					lowerCamelCase_						=			nn.ModuleList()
					for i in range(13 ):
									lowerCamelCase_						=			out_channels

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

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

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

					lowerCamelCase_						=			nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None

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



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase )				->       Optional[int]:
					raise NotImplementedError



	@add_start_docstrings_to_model_forward(lowercase )
	@add_code_sample_docstrings(
	    checkpoint=_CHECKPOINT_FOR_DOC						,  output_type=lowercase						,  config_class=_CONFIG_FOR_DOC						,  modality="vision"						,  expected_output=_EXPECTED_OUTPUT_SHAPE						,  )
	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase = None						,  lowercase = None						,  lowercase = None						,  )				->       Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:
					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.conv_stem(lowercase )

					lowerCamelCase_						=			() if output_hidden_states else None

					for i, layer_module in enumerate(self.layer ):
									lowerCamelCase_						=			layer_module(lowercase )

									if output_hidden_states:
													lowerCamelCase_						=			all_hidden_states + (hidden_states,)

					lowerCamelCase_						=			hidden_states

					if self.pooler is not None:
									lowerCamelCase_						=			torch.flatten(self.pooler(lowercase )						,  start_dim=1 )
					else:
									lowerCamelCase_						=			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=lowercase						,  pooler_output=lowercase						,  hidden_states=lowercase						,  )




@add_start_docstrings(
    '\n    MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    '			,       snake_case_			,       )
class     _SCREAMING_SNAKE_CASE     (      snake_case_						):



	def __init__(    self						,  lowercase )				->       None:
					super().__init__(lowercase )

					lowerCamelCase_						=			config.num_labels
					lowerCamelCase_						=			MobileNetVaModel(lowercase )

					lowerCamelCase_						=			self.mobilenet_va.layer[-1].convolution.out_channels

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

					lowerCamelCase_						=			self.mobilenet_va(lowercase						,  output_hidden_states=lowercase						,  return_dict=lowercase )

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

					lowerCamelCase_						=			self.classifier(self.dropout(lowercase ) )

					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(lowercase						,  lowercase )
									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(lowercase						,  lowercase )

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

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



'''simple docstring'''





import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()




class        __A      ( unittest.TestCase	):



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



    @property
    def 					_lowercase						(self    :    str ):
         UpperCAmelCase_           =   1
         UpperCAmelCase_           =   3
         UpperCAmelCase_           =   (32, 32)

         UpperCAmelCase_           =   floats_tensor((batch_size, num_channels) + sizes   ,			rng=random.Random(0 ) ).to(__a )
         return image



    @property
    def 					_lowercase						(self    :    int ):
         torch.manual_seed(0 )
         UpperCAmelCase_           =   UNetaDConditionModel(
             block_out_channels=(32, 32, 64)   ,			layers_per_block=2   ,			sample_size=32   ,			in_channels=7   ,			out_channels=4   ,			down_block_types=("DownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D")   ,			up_block_types=("CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "UpBlock2D")   ,			cross_attention_dim=32   ,			attention_head_dim=8   ,			use_linear_projection=__a   ,			only_cross_attention=(True, True, False)   ,			num_class_embeds=100   ,			)
         return model



    @property
    def 					_lowercase						(self    :    Any ):
         torch.manual_seed(0 )
         UpperCAmelCase_           =   AutoencoderKL(
             block_out_channels=[32, 32, 64]   ,			in_channels=3   ,			out_channels=3   ,			down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D"]   ,			up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"]   ,			latent_channels=4   ,			)
         return model



    @property
    def 					_lowercase						(self    :    Optional[Any] ):
         torch.manual_seed(0 )
         UpperCAmelCase_           =   CLIPTextConfig(
             bos_token_id=0   ,			eos_token_id=2   ,			hidden_size=32   ,			intermediate_size=37   ,			layer_norm_eps=1E-05   ,			num_attention_heads=4   ,			num_hidden_layers=5   ,			pad_token_id=1   ,			vocab_size=1000   ,			hidden_act="gelu"   ,			projection_dim=512   ,			)
         return CLIPTextModel(__a )



    def 					_lowercase						(self    :    Any ):
         UpperCAmelCase_           =   "cpu"  # ensure determinism for the device-dependent torch.Generator
         UpperCAmelCase_           =   self.dummy_cond_unet_upscale
         UpperCAmelCase_           =   DDPMScheduler()
         UpperCAmelCase_           =   DDIMScheduler(prediction_type="v_prediction" )
         UpperCAmelCase_           =   self.dummy_vae
         UpperCAmelCase_           =   self.dummy_text_encoder
         UpperCAmelCase_           =   CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )

         UpperCAmelCase_           =   self.dummy_image.cpu().permute(0   ,			2   ,			3   ,			1 )[0]
         UpperCAmelCase_           =   Image.fromarray(np.uinta(__a ) ).convert("RGB" ).resize((64, 64) )

         # make sure here that pndm scheduler skips prk
         UpperCAmelCase_           =   StableDiffusionUpscalePipeline(
             unet=__a   ,			low_res_scheduler=__a   ,			scheduler=__a   ,			vae=__a   ,			text_encoder=__a   ,			tokenizer=__a   ,			max_noise_level=350   ,			)
         UpperCAmelCase_           =   sd_pipe.to(__a )
         sd_pipe.set_progress_bar_config(disable=__a )

         UpperCAmelCase_           =   "A painting of a squirrel eating a burger"
         UpperCAmelCase_           =   torch.Generator(device=__a ).manual_seed(0 )
         UpperCAmelCase_           =   sd_pipe(
             [prompt]   ,			image=__a   ,			generator=__a   ,			guidance_scale=6.0   ,			noise_level=20   ,			num_inference_steps=2   ,			output_type="np"   ,			)

         UpperCAmelCase_           =   output.images

         UpperCAmelCase_           =   torch.Generator(device=__a ).manual_seed(0 )
         UpperCAmelCase_           =   sd_pipe(
             [prompt]   ,			image=__a   ,			generator=__a   ,			guidance_scale=6.0   ,			noise_level=20   ,			num_inference_steps=2   ,			output_type="np"   ,			return_dict=__a   ,			)[0]

         UpperCAmelCase_           =   image[0, -3:, -3:, -1]
         UpperCAmelCase_           =   image_from_tuple[0, -3:, -3:, -1]

         UpperCAmelCase_           =   low_res_image.size[0] * 4
         assert image.shape == (1, expected_height_width, expected_height_width, 3)
         UpperCAmelCase_           =   np.array([0.31_13, 0.39_10, 0.42_72, 0.48_59, 0.50_61, 0.46_52, 0.53_62, 0.57_15, 0.56_61] )

         assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
         assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2



    def 					_lowercase						(self    :    Optional[int] ):
         UpperCAmelCase_           =   "cpu"  # ensure determinism for the device-dependent torch.Generator
         UpperCAmelCase_           =   self.dummy_cond_unet_upscale
         UpperCAmelCase_           =   DDPMScheduler()
         UpperCAmelCase_           =   DDIMScheduler(prediction_type="v_prediction" )
         UpperCAmelCase_           =   self.dummy_vae
         UpperCAmelCase_           =   self.dummy_text_encoder
         UpperCAmelCase_           =   CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )

         UpperCAmelCase_           =   self.dummy_image.cpu().permute(0   ,			2   ,			3   ,			1 )[0]
         UpperCAmelCase_           =   Image.fromarray(np.uinta(__a ) ).convert("RGB" ).resize((64, 64) )

         # make sure here that pndm scheduler skips prk
         UpperCAmelCase_           =   StableDiffusionUpscalePipeline(
             unet=__a   ,			low_res_scheduler=__a   ,			scheduler=__a   ,			vae=__a   ,			text_encoder=__a   ,			tokenizer=__a   ,			max_noise_level=350   ,			)
         UpperCAmelCase_           =   sd_pipe.to(__a )
         sd_pipe.set_progress_bar_config(disable=__a )

         UpperCAmelCase_           =   "A painting of a squirrel eating a burger"
         UpperCAmelCase_           =   sd_pipe(
             2 * [prompt]   ,			image=2 * [low_res_image]   ,			guidance_scale=6.0   ,			noise_level=20   ,			num_inference_steps=2   ,			output_type="np"   ,			)
         UpperCAmelCase_           =   output.images
         assert image.shape[0] == 2

         UpperCAmelCase_           =   torch.Generator(device=__a ).manual_seed(0 )
         UpperCAmelCase_           =   sd_pipe(
             [prompt]   ,			image=__a   ,			generator=__a   ,			num_images_per_prompt=2   ,			guidance_scale=6.0   ,			noise_level=20   ,			num_inference_steps=2   ,			output_type="np"   ,			)
         UpperCAmelCase_           =   output.images
         assert image.shape[0] == 2






    @unittest.skipIf(torch_device != "cuda"   ,			"This test requires a GPU" )
    def 					_lowercase						(self    :    str ):
         UpperCAmelCase_           =   self.dummy_cond_unet_upscale
         UpperCAmelCase_           =   DDPMScheduler()
         UpperCAmelCase_           =   DDIMScheduler(prediction_type="v_prediction" )
         UpperCAmelCase_           =   self.dummy_vae
         UpperCAmelCase_           =   self.dummy_text_encoder
         UpperCAmelCase_           =   CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )

         UpperCAmelCase_           =   self.dummy_image.cpu().permute(0   ,			2   ,			3   ,			1 )[0]
         UpperCAmelCase_           =   Image.fromarray(np.uinta(__a ) ).convert("RGB" ).resize((64, 64) )

         # put models in fp16, except vae as it overflows in fp16
         UpperCAmelCase_           =   unet.half()
         UpperCAmelCase_           =   text_encoder.half()

         # make sure here that pndm scheduler skips prk
         UpperCAmelCase_           =   StableDiffusionUpscalePipeline(
             unet=__a   ,			low_res_scheduler=__a   ,			scheduler=__a   ,			vae=__a   ,			text_encoder=__a   ,			tokenizer=__a   ,			max_noise_level=350   ,			)
         UpperCAmelCase_           =   sd_pipe.to(__a )
         sd_pipe.set_progress_bar_config(disable=__a )

         UpperCAmelCase_           =   "A painting of a squirrel eating a burger"
         UpperCAmelCase_           =   torch.manual_seed(0 )
         UpperCAmelCase_           =   sd_pipe(
             [prompt]   ,			image=__a   ,			generator=__a   ,			num_inference_steps=2   ,			output_type="np"   ,			).images

         UpperCAmelCase_           =   low_res_image.size[0] * 4
         assert image.shape == (1, expected_height_width, expected_height_width, 3)




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



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



    def 					_lowercase						(self    :    List[Any] ):
         UpperCAmelCase_           =   load_image(
             "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
             "/sd2-upscale/low_res_cat.png" )
         UpperCAmelCase_           =   load_numpy(
             "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale"
             "/upsampled_cat.npy" )

         UpperCAmelCase_           =   "stabilityai/stable-diffusion-x4-upscaler"
         UpperCAmelCase_           =   StableDiffusionUpscalePipeline.from_pretrained(__a )
         pipe.to(__a )
         pipe.set_progress_bar_config(disable=__a )
         pipe.enable_attention_slicing()

         UpperCAmelCase_           =   "a cat sitting on a park bench"

         UpperCAmelCase_           =   torch.manual_seed(0 )
         UpperCAmelCase_           =   pipe(
             prompt=__a   ,			image=__a   ,			generator=__a   ,			output_type="np"   ,			)
         UpperCAmelCase_           =   output.images[0]

         assert image.shape == (512, 512, 3)
         assert np.abs(expected_image - image ).max() < 1E-3



    def 					_lowercase						(self    :    Tuple ):
         UpperCAmelCase_           =   load_image(
             "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
             "/sd2-upscale/low_res_cat.png" )
         UpperCAmelCase_           =   load_numpy(
             "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale"
             "/upsampled_cat_fp16.npy" )

         UpperCAmelCase_           =   "stabilityai/stable-diffusion-x4-upscaler"
         UpperCAmelCase_           =   StableDiffusionUpscalePipeline.from_pretrained(
             __a   ,			torch_dtype=torch.floataa   ,			)
         pipe.to(__a )
         pipe.set_progress_bar_config(disable=__a )
         pipe.enable_attention_slicing()

         UpperCAmelCase_           =   "a cat sitting on a park bench"

         UpperCAmelCase_           =   torch.manual_seed(0 )
         UpperCAmelCase_           =   pipe(
             prompt=__a   ,			image=__a   ,			generator=__a   ,			output_type="np"   ,			)
         UpperCAmelCase_           =   output.images[0]

         assert image.shape == (512, 512, 3)
         assert np.abs(expected_image - image ).max() < 5E-1






    def 					_lowercase						(self    :    List[Any] ):
         torch.cuda.empty_cache()
         torch.cuda.reset_max_memory_allocated()
         torch.cuda.reset_peak_memory_stats()

         UpperCAmelCase_           =   load_image(
             "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
             "/sd2-upscale/low_res_cat.png" )

         UpperCAmelCase_           =   "stabilityai/stable-diffusion-x4-upscaler"
         UpperCAmelCase_           =   StableDiffusionUpscalePipeline.from_pretrained(
             __a   ,			torch_dtype=torch.floataa   ,			)
         pipe.to(__a )
         pipe.set_progress_bar_config(disable=__a )
         pipe.enable_attention_slicing(1 )
         pipe.enable_sequential_cpu_offload()

         UpperCAmelCase_           =   "a cat sitting on a park bench"

         UpperCAmelCase_           =   torch.manual_seed(0 )
         UpperCAmelCase_           =   pipe(
             prompt=__a   ,			image=__a   ,			generator=__a   ,			num_inference_steps=5   ,			output_type="np"   ,			)

         UpperCAmelCase_           =   torch.cuda.max_memory_allocated()
         # make sure that less than 2.9 GB is allocated
         assert mem_bytes < 2.9 * 10**9




