





from typing import Optional, Tuple, Union

import tensorflow as tf

from ...activations_tf import ACTaFN
from ...modeling_tf_outputs import (
    TFBaseModelOutputWithNoAttention,
    TFBaseModelOutputWithPoolingAndNoAttention,
    TFImageClassifierOutputWithNoAttention,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_resnet import ResNetConfig


snake_case_				=      logging.get_logger(__name__)

# General docstring
snake_case_				=      '''ResNetConfig'''

# Base docstring
snake_case_				=      '''microsoft/resnet-50'''
snake_case_				=      [1, 2_0_4_8, 7, 7]

# Image classification docstring
snake_case_				=      '''microsoft/resnet-50'''
snake_case_				=      '''tiger cat'''

snake_case_				=      [
    '''microsoft/resnet-50''',
    # See all resnet models at https://huggingface.co/models?filter=resnet
]
class 							snake_case_		(      tf.keras.layers.Layer):







		def __init__(		self      ,  __lowercase      ,  __lowercase = 3      ,  __lowercase = 1      ,  __lowercase = "relu"      ,  **__lowercase )					-> None:
				super().__init__(**__lowercase )
				lowerCamelCase :			Union[str, Any]    		=kernel_size // 2
				lowerCamelCase :			Optional[int]    		=tf.keras.layers.ConvaD(
				    __lowercase      ,  kernel_size=__lowercase      ,  strides=__lowercase      ,  padding='''valid'''      ,  use_bias=__lowercase      ,  name='''convolution''' )
				# Use same default momentum and epsilon as PyTorch equivalent
				lowerCamelCase :			Dict    		=tf.keras.layers.BatchNormalization(epsilon=1e-5      ,  momentum=0.9      ,  name='''normalization''' )
				lowerCamelCase :			List[Any]    		=ACTaFN[activation] if activation is not None else tf.keras.layers.Activation('''linear''' )







		def       __lowercase (		self      ,  __lowercase )					-> tf.Tensor:
				# Pad to match that done in the PyTorch Conv2D model
				lowerCamelCase :			Tuple    		=(self.pad_value, self.pad_value)
				lowerCamelCase :			List[str]    		=tf.pad(__lowercase      ,  [(0, 0), height_pad, width_pad, (0, 0)] )
				lowerCamelCase :			List[str]    		=self.conv(__lowercase )
				return hidden_state







		def       __lowercase (		self      ,  __lowercase      ,  __lowercase = False )					-> tf.Tensor:
				lowerCamelCase :			List[Any]    		=self.convolution(__lowercase )
				lowerCamelCase :			Optional[int]    		=self.normalization(__lowercase      ,  training=__lowercase )
				lowerCamelCase :			int    		=self.activation(__lowercase )
				return hidden_state

class 							snake_case_		(      tf.keras.layers.Layer):







		def __init__(		self      ,  __lowercase      ,  **__lowercase )					-> None:
				super().__init__(**__lowercase )
				lowerCamelCase :			int    		=TFResNetConvLayer(
				    config.embedding_size      ,  kernel_size=7      ,  stride=2      ,  activation=config.hidden_act      ,  name='''embedder'''      ,  )
				lowerCamelCase :			Dict    		=tf.keras.layers.MaxPoolaD(pool_size=3      ,  strides=2      ,  padding='''valid'''      ,  name='''pooler''' )
				lowerCamelCase :			int    		=config.num_channels







		def       __lowercase (		self      ,  __lowercase      ,  __lowercase = False )					-> tf.Tensor:
				lowerCamelCase		, lowerCamelCase		, lowerCamelCase		, lowerCamelCase :			List[str]    		=shape_list(__lowercase )
				if tf.executing_eagerly() and 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.''' )
				lowerCamelCase :			str    		=pixel_values
				lowerCamelCase :			Any    		=self.embedder(__lowercase )
				lowerCamelCase :			Optional[int]    		=tf.pad(__lowercase      ,  [[0, 0], [1, 1], [1, 1], [0, 0]] )
				lowerCamelCase :			List[str]    		=self.pooler(__lowercase )
				return hidden_state

class 							snake_case_		(      tf.keras.layers.Layer):







		def __init__(		self      ,  __lowercase      ,  __lowercase = 2      ,  **__lowercase )					-> None:
				super().__init__(**__lowercase )
				lowerCamelCase :			List[Any]    		=tf.keras.layers.ConvaD(
				    __lowercase      ,  kernel_size=1      ,  strides=__lowercase      ,  use_bias=__lowercase      ,  name='''convolution''' )
				# Use same default momentum and epsilon as PyTorch equivalent
				lowerCamelCase :			Optional[Any]    		=tf.keras.layers.BatchNormalization(epsilon=1e-5      ,  momentum=0.9      ,  name='''normalization''' )







		def       __lowercase (		self      ,  __lowercase      ,  __lowercase = False )					-> tf.Tensor:
				lowerCamelCase :			Union[str, Any]    		=x
				lowerCamelCase :			str    		=self.convolution(__lowercase )
				lowerCamelCase :			int    		=self.normalization(__lowercase      ,  training=__lowercase )
				return hidden_state

class 							snake_case_		(      tf.keras.layers.Layer):







		def __init__(		self      ,  __lowercase      ,  __lowercase      ,  __lowercase = 1      ,  __lowercase = "relu"      ,  **__lowercase )					-> None:
				super().__init__(**__lowercase )
				lowerCamelCase :			int    		=in_channels != out_channels or stride != 1
				lowerCamelCase :			str    		=TFResNetConvLayer(__lowercase      ,  stride=__lowercase      ,  name='''layer.0''' )
				lowerCamelCase :			str    		=TFResNetConvLayer(__lowercase      ,  activation=__lowercase      ,  name='''layer.1''' )
				lowerCamelCase :			Any    		=(
				    TFResNetShortCut(__lowercase      ,  stride=__lowercase      ,  name='''shortcut''' )
				    if should_apply_shortcut
				    else tf.keras.layers.Activation('''linear'''      ,  name='''shortcut''' )
				)
				lowerCamelCase :			Optional[Any]    		=ACTaFN[activation]







		def       __lowercase (		self      ,  __lowercase      ,  __lowercase = False )					-> tf.Tensor:
				lowerCamelCase :			Dict    		=hidden_state
				lowerCamelCase :			Union[str, Any]    		=self.conva(__lowercase      ,  training=__lowercase )
				lowerCamelCase :			Tuple    		=self.conva(__lowercase      ,  training=__lowercase )
				lowerCamelCase :			Dict    		=self.shortcut(__lowercase      ,  training=__lowercase )
				hidden_state += residual
				lowerCamelCase :			List[Any]    		=self.activation(__lowercase )
				return hidden_state

class 							snake_case_		(      tf.keras.layers.Layer):







		def __init__(		self      ,  __lowercase      ,  __lowercase      ,  __lowercase = 1      ,  __lowercase = "relu"      ,  __lowercase = 4      ,  **__lowercase      ,  )					-> None:
				super().__init__(**__lowercase )
				lowerCamelCase :			Dict    		=in_channels != out_channels or stride != 1
				lowerCamelCase :			Union[str, Any]    		=out_channels // reduction
				lowerCamelCase :			Optional[Any]    		=TFResNetConvLayer(__lowercase      ,  kernel_size=1      ,  name='''layer.0''' )
				lowerCamelCase :			int    		=TFResNetConvLayer(__lowercase      ,  stride=__lowercase      ,  name='''layer.1''' )
				lowerCamelCase :			Dict    		=TFResNetConvLayer(__lowercase      ,  kernel_size=1      ,  activation=__lowercase      ,  name='''layer.2''' )
				lowerCamelCase :			Union[str, Any]    		=(
				    TFResNetShortCut(__lowercase      ,  stride=__lowercase      ,  name='''shortcut''' )
				    if should_apply_shortcut
				    else tf.keras.layers.Activation('''linear'''      ,  name='''shortcut''' )
				)
				lowerCamelCase :			List[str]    		=ACTaFN[activation]







		def       __lowercase (		self      ,  __lowercase      ,  __lowercase = False )					-> tf.Tensor:
				lowerCamelCase :			Union[str, Any]    		=hidden_state
				lowerCamelCase :			Optional[int]    		=self.conva(__lowercase      ,  training=__lowercase )
				lowerCamelCase :			Tuple    		=self.conva(__lowercase      ,  training=__lowercase )
				lowerCamelCase :			List[Any]    		=self.conva(__lowercase      ,  training=__lowercase )
				lowerCamelCase :			List[str]    		=self.shortcut(__lowercase      ,  training=__lowercase )
				hidden_state += residual
				lowerCamelCase :			Dict    		=self.activation(__lowercase )
				return hidden_state

class 							snake_case_		(      tf.keras.layers.Layer):







		def __init__(		self      ,  __lowercase      ,  __lowercase      ,  __lowercase      ,  __lowercase = 2      ,  __lowercase = 2      ,  **__lowercase )					-> None:
				super().__init__(**__lowercase )

				lowerCamelCase :			Tuple    		=TFResNetBottleNeckLayer if config.layer_type == '''bottleneck''' else TFResNetBasicLayer

				lowerCamelCase :			Tuple    		=[layer(__lowercase      ,  __lowercase      ,  stride=__lowercase      ,  activation=config.hidden_act      ,  name='''layers.0''' )]
				layers += [
				    layer(__lowercase      ,  __lowercase      ,  activation=config.hidden_act      ,  name=F"layers.{i + 1}" )
				    for i in range(depth - 1 )
				]
				lowerCamelCase :			List[str]    		=layers







		def       __lowercase (		self      ,  __lowercase      ,  __lowercase = False )					-> tf.Tensor:
				for layer in self.stage_layers:
						lowerCamelCase :			List[str]    		=layer(__lowercase      ,  training=__lowercase )
				return hidden_state

class 							snake_case_		(      tf.keras.layers.Layer):







		def __init__(		self      ,  __lowercase      ,  **__lowercase )					-> None:
				super().__init__(**__lowercase )
				# based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
				lowerCamelCase :			str    		=[
				    TFResNetStage(
				        __lowercase      ,  config.embedding_size      ,  config.hidden_sizes[0]      ,  stride=2 if config.downsample_in_first_stage else 1      ,  depth=config.depths[0]      ,  name='''stages.0'''      ,  )
				]
				for i, (in_channels, out_channels, depth) in enumerate(
				    zip(config.hidden_sizes      ,  config.hidden_sizes[1:]      ,  config.depths[1:] ) ):
						self.stages.append(TFResNetStage(__lowercase      ,  __lowercase      ,  __lowercase      ,  depth=__lowercase      ,  name=F"stages.{i + 1}" ) )







		def       __lowercase (		self      ,  __lowercase      ,  __lowercase = False      ,  __lowercase = True      ,  __lowercase = False      ,  )					-> TFBaseModelOutputWithNoAttention:
				lowerCamelCase :			Optional[int]    		=() if output_hidden_states else None

				for stage_module in self.stages:
						if output_hidden_states:
								lowerCamelCase :			List[str]    		=hidden_states + (hidden_state,)

						lowerCamelCase :			int    		=stage_module(__lowercase      ,  training=__lowercase )

				if output_hidden_states:
						lowerCamelCase :			List[str]    		=hidden_states + (hidden_state,)

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

				return TFBaseModelOutputWithNoAttention(last_hidden_state=__lowercase      ,  hidden_states=__lowercase )

class 							snake_case_		(      _A):
		lowerCamelCase     :str							=  ResNetConfig
		lowerCamelCase     :str							=  "resnet"
		lowerCamelCase     :int							=  "pixel_values"







		@property
		def       __lowercase (		self )					-> Optional[Any]:
				return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_2_4, 2_2_4)      ,  dtype=tf.floataa )}

snake_case_				=      r'''
    This model is a TensorFlow
    [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a
    regular TensorFlow Module and refer to the TensorFlow documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`ResNetConfig`]): 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 [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
'''


snake_case_				=      r'''
    Args:
        pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConvNextImageProcessor.__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.
'''
@keras_serializable
class 							snake_case_		(      tf.keras.layers.Layer):
		lowerCamelCase     :List[Any]							=  ResNetConfig







		def __init__(		self      ,  __lowercase      ,  **__lowercase )					-> None:
				super().__init__(**__lowercase )
				lowerCamelCase :			List[str]    		=config
				lowerCamelCase :			Any    		=TFResNetEmbeddings(__lowercase      ,  name='''embedder''' )
				lowerCamelCase :			int    		=TFResNetEncoder(__lowercase      ,  name='''encoder''' )
				lowerCamelCase :			List[str]    		=tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowercase )







		@unpack_inputs
		def       __lowercase (		self      ,  __lowercase      ,  __lowercase = None      ,  __lowercase = None      ,  __lowercase = False      ,  )					-> Union[Tuple[tf.Tensor], TFBaseModelOutputWithPoolingAndNoAttention]:
				lowerCamelCase :			Any    		=(
				    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
				)
				lowerCamelCase :			str    		=return_dict if return_dict is not None else self.config.use_return_dict

				# TF 2.0 image layers can't use NCHW format when running on CPU.
				# We transpose to NHWC format and then transpose back after the full forward pass.
				# (batch_size, num_channels, height, width) -> (batch_size, height, width, num_channels)
				lowerCamelCase :			Any    		=tf.transpose(__lowercase      ,  perm=[0, 2, 3, 1] )
				lowerCamelCase :			Any    		=self.embedder(__lowercase      ,  training=__lowercase )

				lowerCamelCase :			int    		=self.encoder(
				    __lowercase      ,  output_hidden_states=__lowercase      ,  return_dict=__lowercase      ,  training=__lowercase )

				lowerCamelCase :			Union[str, Any]    		=encoder_outputs[0]

				lowerCamelCase :			Any    		=self.pooler(__lowercase )

				# Transpose all the outputs to the NCHW format
				# (batch_size, height, width, num_channels) -> (batch_size, num_channels, height, width)
				lowerCamelCase :			List[str]    		=tf.transpose(__lowercase      ,  (0, 3, 1, 2) )
				lowerCamelCase :			Optional[Any]    		=tf.transpose(__lowercase      ,  (0, 3, 1, 2) )
				lowerCamelCase :			Union[str, Any]    		=()
				for hidden_state in encoder_outputs[1:]:
						lowerCamelCase :			str    		=hidden_states + tuple(tf.transpose(__lowercase      ,  (0, 3, 1, 2) ) for h in hidden_state )

				if not return_dict:
						return (last_hidden_state, pooled_output) + hidden_states

				lowerCamelCase :			Dict    		=hidden_states if output_hidden_states else None

				return TFBaseModelOutputWithPoolingAndNoAttention(
				    last_hidden_state=__lowercase      ,  pooler_output=__lowercase      ,  hidden_states=__lowercase      ,  )

@add_start_docstrings(
    "The bare ResNet model outputting raw features without any specific head on top."    ,       _A    ,       )
class 							snake_case_		(      _A):







		def __init__(		self      ,  __lowercase      ,  **__lowercase )					-> None:
				super().__init__(__lowercase      ,  **__lowercase )
				lowerCamelCase :			int    		=TFResNetMainLayer(config=__lowercase      ,  name='''resnet''' )







		@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      ,  )
		@unpack_inputs
		def       __lowercase (		self      ,  __lowercase      ,  __lowercase = None      ,  __lowercase = None      ,  __lowercase = False      ,  )					-> Union[Tuple[tf.Tensor], TFBaseModelOutputWithPoolingAndNoAttention]:
				lowerCamelCase :			str    		=(
				    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
				)
				lowerCamelCase :			List[Any]    		=return_dict if return_dict is not None else self.config.use_return_dict

				lowerCamelCase :			Optional[int]    		=self.resnet(
				    pixel_values=__lowercase      ,  output_hidden_states=__lowercase      ,  return_dict=__lowercase      ,  training=__lowercase      ,  )
				return resnet_outputs

@add_start_docstrings(
    "\n    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    "    ,       _A    ,       )
class 							snake_case_		(      _A    ,       _A):







		def __init__(		self      ,  __lowercase      ,  **__lowercase )					-> None:
				super().__init__(__lowercase      ,  **__lowercase )
				lowerCamelCase :			List[str]    		=config.num_labels
				lowerCamelCase :			List[Any]    		=TFResNetMainLayer(__lowercase      ,  name='''resnet''' )
				# classification head
				lowerCamelCase :			str    		=(
				    tf.keras.layers.Dense(config.num_labels      ,  name='''classifier.1''' )
				    if config.num_labels > 0
				    else tf.keras.layers.Activation('''linear'''      ,  name='''classifier.1''' )
				)







		def       __lowercase (		self      ,  __lowercase )					-> tf.Tensor:
				lowerCamelCase :			Any    		=tf.keras.layers.Flatten()(__lowercase )
				lowerCamelCase :			Tuple    		=self.classifier_layer(__lowercase )
				return logits







		@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      ,  )
		@unpack_inputs
		def       __lowercase (		self      ,  __lowercase = None      ,  __lowercase = None      ,  __lowercase = None      ,  __lowercase = None      ,  __lowercase = False      ,  )					-> Union[Tuple[tf.Tensor], TFImageClassifierOutputWithNoAttention]:
				lowerCamelCase :			Optional[Any]    		=return_dict if return_dict is not None else self.config.use_return_dict

				lowerCamelCase :			Tuple    		=self.resnet(
				    __lowercase      ,  output_hidden_states=__lowercase      ,  return_dict=__lowercase      ,  training=__lowercase )

				lowerCamelCase :			Any    		=outputs.pooler_output if return_dict else outputs[1]

				lowerCamelCase :			Optional[int]    		=self.classifier(__lowercase )

				lowerCamelCase :			Optional[int]    		=None if labels is None else self.hf_compute_loss(__lowercase      ,  __lowercase )

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

				return TFImageClassifierOutputWithNoAttention(loss=__lowercase      ,  logits=__lowercase      ,  hidden_states=outputs.hidden_states )








import inspect
from typing import List, Optional, Union

import torch
from torch import nn
from torch.nn import functional as F
from torchvision import transforms
from transformers import CLIPImageProcessor, CLIPModel, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    DPMSolverMultistepScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
class 							snake_case_		(      nn.Module):







		def __init__(		self      ,  __lowercase      ,  __lowercase=1.0 )					-> List[str]:
				super().__init__()

				lowerCamelCase :			Optional[Any]    		=cut_size
				lowerCamelCase :			List[str]    		=cut_power







		def       __lowercase (		self      ,  __lowercase      ,  __lowercase )					-> int:
				lowerCamelCase		, lowerCamelCase :			Any    		=pixel_values.shape[2:4]
				lowerCamelCase :			Any    		=min(__lowercase      ,  __lowercase )
				lowerCamelCase :			int    		=min(__lowercase      ,  __lowercase      ,  self.cut_size )
				lowerCamelCase :			Dict    		=[]
				for _ in range(__lowercase ):
						lowerCamelCase :			Union[str, Any]    		=int(torch.rand([] ) ** self.cut_power * (max_size - min_size) + min_size )
						lowerCamelCase :			Any    		=torch.randint(0      ,  sideX - size + 1      ,  () )
						lowerCamelCase :			Any    		=torch.randint(0      ,  sideY - size + 1      ,  () )
						lowerCamelCase :			Optional[Any]    		=pixel_values[:, :, offsety : offsety + size, offsetx : offsetx + size]
						cutouts.append(F.adaptive_avg_poolad(__lowercase      ,  self.cut_size ) )
				return torch.cat(__lowercase )


def        A__						(							SCREAMING_SNAKE_CASE_				,							SCREAMING_SNAKE_CASE_		) ->  Optional[Any]:
		lowerCamelCase :			str    		=F.normalize(SCREAMING_SNAKE_CASE_				,							dim=-1		)
		lowerCamelCase :			Optional[Any]    		=F.normalize(SCREAMING_SNAKE_CASE_				,							dim=-1		)
		return (x - y).norm(dim=-1		).div(2		).arcsin().pow(2		).mul(2		)


def        A__						(							SCREAMING_SNAKE_CASE_				,							SCREAMING_SNAKE_CASE_		) ->  List[str]:
		for param in model.parameters():
				lowerCamelCase :			List[Any]    		=value



class 							snake_case_		(      _A):







		def __init__(		self      ,  __lowercase      ,  __lowercase      ,  __lowercase      ,  __lowercase      ,  __lowercase      ,  __lowercase      ,  __lowercase      ,  )					-> List[Any]:
				super().__init__()
				self.register_modules(
				    vae=__lowercase      ,  text_encoder=__lowercase      ,  clip_model=__lowercase      ,  tokenizer=__lowercase      ,  unet=__lowercase      ,  scheduler=__lowercase      ,  feature_extractor=__lowercase      ,  )

				lowerCamelCase :			Optional[Any]    		=transforms.Normalize(mean=feature_extractor.image_mean      ,  std=feature_extractor.image_std )
				lowerCamelCase :			int    		=(
				    feature_extractor.size
				    if isinstance(feature_extractor.size      ,  __lowercase )
				    else feature_extractor.size['''shortest_edge''']
				)
				lowerCamelCase :			int    		=MakeCutouts(self.cut_out_size )

				set_requires_grad(self.text_encoder      ,  __lowercase )
				set_requires_grad(self.clip_model      ,  __lowercase )







		def       __lowercase (		self      ,  __lowercase = "auto" )					-> Dict:
				if slice_size == "auto":
						# half the attention head size is usually a good trade-off between
						# speed and memory
						lowerCamelCase :			int    		=self.unet.config.attention_head_dim // 2
				self.unet.set_attention_slice(__lowercase )







		def       __lowercase (		self )					-> List[str]:
				self.enable_attention_slicing(__lowercase )







		def       __lowercase (		self )					-> List[str]:
				set_requires_grad(self.vae      ,  __lowercase )







		def       __lowercase (		self )					-> List[str]:
				set_requires_grad(self.vae      ,  __lowercase )







		def       __lowercase (		self )					-> Dict:
				set_requires_grad(self.unet      ,  __lowercase )







		def       __lowercase (		self )					-> Union[str, Any]:
				set_requires_grad(self.unet      ,  __lowercase )







		@torch.enable_grad()
		def       __lowercase (		self      ,  __lowercase      ,  __lowercase      ,  __lowercase      ,  __lowercase      ,  __lowercase      ,  __lowercase      ,  __lowercase      ,  __lowercase      ,  __lowercase=True      ,  )					-> Union[str, Any]:
				lowerCamelCase :			Dict    		=latents.detach().requires_grad_()

				lowerCamelCase :			int    		=self.scheduler.scale_model_input(__lowercase      ,  __lowercase )

				# predict the noise residual
				lowerCamelCase :			Union[str, Any]    		=self.unet(__lowercase      ,  __lowercase      ,  encoder_hidden_states=__lowercase ).sample

				if isinstance(self.scheduler      ,  (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ):
						lowerCamelCase :			Optional[int]    		=self.scheduler.alphas_cumprod[timestep]
						lowerCamelCase :			List[str]    		=1 - alpha_prod_t
						# compute predicted original sample from predicted noise also called
						# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
						lowerCamelCase :			Tuple    		=(latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5

						lowerCamelCase :			List[str]    		=torch.sqrt(__lowercase )
						lowerCamelCase :			str    		=pred_original_sample * (fac) + latents * (1 - fac)
				elif isinstance(self.scheduler      ,  __lowercase ):
						lowerCamelCase :			Optional[int]    		=self.scheduler.sigmas[index]
						lowerCamelCase :			str    		=latents - sigma * noise_pred
				else:
						raise ValueError(F"scheduler type {type(self.scheduler )} not supported" )

				lowerCamelCase :			List[Any]    		=1 / self.vae.config.scaling_factor * sample
				lowerCamelCase :			Optional[Any]    		=self.vae.decode(__lowercase ).sample
				lowerCamelCase :			Dict    		=(image / 2 + 0.5).clamp(0      ,  1 )

				if use_cutouts:
						lowerCamelCase :			Tuple    		=self.make_cutouts(__lowercase      ,  __lowercase )
				else:
						lowerCamelCase :			str    		=transforms.Resize(self.cut_out_size )(__lowercase )
				lowerCamelCase :			List[Any]    		=self.normalize(__lowercase ).to(latents.dtype )

				lowerCamelCase :			Optional[Any]    		=self.clip_model.get_image_features(__lowercase )
				lowerCamelCase :			Optional[int]    		=image_embeddings_clip / image_embeddings_clip.norm(p=2      ,  dim=-1      ,  keepdim=__lowercase )

				if use_cutouts:
						lowerCamelCase :			str    		=spherical_dist_loss(__lowercase      ,  __lowercase )
						lowerCamelCase :			Union[str, Any]    		=dists.view([num_cutouts, sample.shape[0], -1] )
						lowerCamelCase :			Tuple    		=dists.sum(2 ).mean(0 ).sum() * clip_guidance_scale
				else:
						lowerCamelCase :			Union[str, Any]    		=spherical_dist_loss(__lowercase      ,  __lowercase ).mean() * clip_guidance_scale

				lowerCamelCase :			List[Any]    		=-torch.autograd.grad(__lowercase      ,  __lowercase )[0]

				if isinstance(self.scheduler      ,  __lowercase ):
						lowerCamelCase :			Any    		=latents.detach() + grads * (sigma**2)
						lowerCamelCase :			Dict    		=noise_pred_original
				else:
						lowerCamelCase :			Union[str, Any]    		=noise_pred_original - torch.sqrt(__lowercase ) * grads
				return noise_pred, latents







		@torch.no_grad()
		def __call__(		self      ,  __lowercase      ,  __lowercase = 5_1_2      ,  __lowercase = 5_1_2      ,  __lowercase = 5_0      ,  __lowercase = 7.5      ,  __lowercase = 1      ,  __lowercase = 0.0      ,  __lowercase = 1_0_0      ,  __lowercase = None      ,  __lowercase = 4      ,  __lowercase = True      ,  __lowercase = None      ,  __lowercase = None      ,  __lowercase = "pil"      ,  __lowercase = True      ,  )					-> Dict:
				if isinstance(__lowercase      ,  __lowercase ):
						lowerCamelCase :			List[str]    		=1
				elif isinstance(__lowercase      ,  __lowercase ):
						lowerCamelCase :			Dict    		=len(__lowercase )
				else:
						raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(__lowercase )}" )

				if height % 8 != 0 or width % 8 != 0:
						raise ValueError(F"`height` and `width` have to be divisible by 8 but are {height} and {width}." )

				# get prompt text embeddings
				lowerCamelCase :			Optional[int]    		=self.tokenizer(
				    __lowercase      ,  padding='''max_length'''      ,  max_length=self.tokenizer.model_max_length      ,  truncation=__lowercase      ,  return_tensors='''pt'''      ,  )
				lowerCamelCase :			Any    		=self.text_encoder(text_input.input_ids.to(self.device ) )[0]
				# duplicate text embeddings for each generation per prompt
				lowerCamelCase :			Union[str, Any]    		=text_embeddings.repeat_interleave(__lowercase      ,  dim=0 )

				if clip_guidance_scale > 0:
						if clip_prompt is not None:
								lowerCamelCase :			Dict    		=self.tokenizer(
								    __lowercase      ,  padding='''max_length'''      ,  max_length=self.tokenizer.model_max_length      ,  truncation=__lowercase      ,  return_tensors='''pt'''      ,  ).input_ids.to(self.device )
						else:
								lowerCamelCase :			List[Any]    		=text_input.input_ids.to(self.device )
						lowerCamelCase :			Dict    		=self.clip_model.get_text_features(__lowercase )
						lowerCamelCase :			int    		=text_embeddings_clip / text_embeddings_clip.norm(p=2      ,  dim=-1      ,  keepdim=__lowercase )
						# duplicate text embeddings clip for each generation per prompt
						lowerCamelCase :			List[Any]    		=text_embeddings_clip.repeat_interleave(__lowercase      ,  dim=0 )

				# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
				# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
				# corresponds to doing no classifier free guidance.
				lowerCamelCase :			int    		=guidance_scale > 1.0
				# get unconditional embeddings for classifier free guidance
				if do_classifier_free_guidance:
						lowerCamelCase :			Union[str, Any]    		=text_input.input_ids.shape[-1]
						lowerCamelCase :			str    		=self.tokenizer(['''''']      ,  padding='''max_length'''      ,  max_length=__lowercase      ,  return_tensors='''pt''' )
						lowerCamelCase :			Any    		=self.text_encoder(uncond_input.input_ids.to(self.device ) )[0]
						# duplicate unconditional embeddings for each generation per prompt
						lowerCamelCase :			str    		=uncond_embeddings.repeat_interleave(__lowercase      ,  dim=0 )

						# For classifier free guidance, we need to do two forward passes.
						# Here we concatenate the unconditional and text embeddings into a single batch
						# to avoid doing two forward passes
						lowerCamelCase :			Optional[Any]    		=torch.cat([uncond_embeddings, text_embeddings] )

				# get the initial random noise unless the user supplied it

				# Unlike in other pipelines, latents need to be generated in the target device
				# for 1-to-1 results reproducibility with the CompVis implementation.
				# However this currently doesn't work in `mps`.
				lowerCamelCase :			Optional[int]    		=(batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
				lowerCamelCase :			List[Any]    		=text_embeddings.dtype
				if latents is None:
						if self.device.type == "mps":
								# randn does not work reproducibly on mps
								lowerCamelCase :			Optional[int]    		=torch.randn(__lowercase      ,  generator=__lowercase      ,  device='''cpu'''      ,  dtype=__lowercase ).to(
								    self.device )
						else:
								lowerCamelCase :			int    		=torch.randn(__lowercase      ,  generator=__lowercase      ,  device=self.device      ,  dtype=__lowercase )
				else:
						if latents.shape != latents_shape:
								raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {latents_shape}" )
						lowerCamelCase :			Optional[int]    		=latents.to(self.device )

				# set timesteps
				lowerCamelCase :			Optional[Any]    		='''offset''' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() )
				lowerCamelCase :			List[Any]    		={}
				if accepts_offset:
						lowerCamelCase :			Tuple    		=1

				self.scheduler.set_timesteps(__lowercase      ,  **__lowercase )

				# Some schedulers like PNDM have timesteps as arrays
				# It's more optimized to move all timesteps to correct device beforehand
				lowerCamelCase :			Optional[int]    		=self.scheduler.timesteps.to(self.device )

				# scale the initial noise by the standard deviation required by the scheduler
				lowerCamelCase :			List[Any]    		=latents * self.scheduler.init_noise_sigma

				# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
				# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
				# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
				# and should be between [0, 1]
				lowerCamelCase :			Tuple    		='''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() )
				lowerCamelCase :			Union[str, Any]    		={}
				if accepts_eta:
						lowerCamelCase :			List[str]    		=eta

				# check if the scheduler accepts generator
				lowerCamelCase :			Tuple    		='''generator''' in set(inspect.signature(self.scheduler.step ).parameters.keys() )
				if accepts_generator:
						lowerCamelCase :			int    		=generator

				for i, t in enumerate(self.progress_bar(__lowercase ) ):
						# expand the latents if we are doing classifier free guidance
						lowerCamelCase :			int    		=torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
						lowerCamelCase :			int    		=self.scheduler.scale_model_input(__lowercase      ,  __lowercase )

						# predict the noise residual
						lowerCamelCase :			Optional[int]    		=self.unet(__lowercase      ,  __lowercase      ,  encoder_hidden_states=__lowercase ).sample

						# perform classifier free guidance
						if do_classifier_free_guidance:
								lowerCamelCase		, lowerCamelCase :			Optional[int]    		=noise_pred.chunk(2 )
								lowerCamelCase :			Union[str, Any]    		=noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

						# perform clip guidance
						if clip_guidance_scale > 0:
								lowerCamelCase :			List[Any]    		=(
								    text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings
								)
								lowerCamelCase		, lowerCamelCase :			Union[str, Any]    		=self.cond_fn(
								    __lowercase      ,  __lowercase      ,  __lowercase      ,  __lowercase      ,  __lowercase      ,  __lowercase      ,  __lowercase      ,  __lowercase      ,  __lowercase      ,  )

						# compute the previous noisy sample x_t -> x_t-1
						lowerCamelCase :			Dict    		=self.scheduler.step(__lowercase      ,  __lowercase      ,  __lowercase      ,  **__lowercase ).prev_sample

				# scale and decode the image latents with vae
				lowerCamelCase :			Tuple    		=1 / self.vae.config.scaling_factor * latents
				lowerCamelCase :			str    		=self.vae.decode(__lowercase ).sample

				lowerCamelCase :			Optional[int]    		=(image / 2 + 0.5).clamp(0      ,  1 )
				lowerCamelCase :			Union[str, Any]    		=image.cpu().permute(0      ,  2      ,  3      ,  1 ).numpy()

				if output_type == "pil":
						lowerCamelCase :			Optional[Any]    		=self.numpy_to_pil(__lowercase )

				if not return_dict:
						return (image, None)

				return StableDiffusionPipelineOutput(images=__lowercase      ,  nsfw_content_detected=__lowercase )

