
"""simple docstring"""


from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block




@dataclass
class    __lowerCamelCase     (   lowerCAmelCase ):
				a__:			torch.FloatTensor




class    __lowerCamelCase     (   lowerCAmelCase	,  lowerCAmelCase ):




				@register_to_config
				def __init__(							self       ,	UpperCAmelCase = None       ,	UpperCAmelCase = 3       ,	UpperCAmelCase = 3       ,	UpperCAmelCase = False       ,	UpperCAmelCase = "positional"       ,	UpperCAmelCase = 0       ,	UpperCAmelCase = True       ,	UpperCAmelCase = ("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D")       ,	UpperCAmelCase = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D")       ,	UpperCAmelCase = (224, 448, 672, 896)       ,	UpperCAmelCase = 2       ,	UpperCAmelCase = 1       ,	UpperCAmelCase = 1       ,	UpperCAmelCase = "conv"       ,	UpperCAmelCase = "conv"       ,	UpperCAmelCase = "silu"       ,	UpperCAmelCase = 8       ,	UpperCAmelCase = 32       ,	UpperCAmelCase = 1e-5       ,	UpperCAmelCase = "default"       ,	UpperCAmelCase = True       ,	UpperCAmelCase = None       ,	UpperCAmelCase = None       ,	):
							super().__init__()

							lowerCamelCase_ 		=     sample_size
							lowerCamelCase_ 		=     block_out_channels[0] * 4

							# Check inputs
							if len(UpperCAmelCase      ) != len(UpperCAmelCase      ):
										raise ValueError(
										    f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}."      )

							if len(UpperCAmelCase      ) != len(UpperCAmelCase      ):
										raise ValueError(
										    f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."      )

							# input
							lowerCamelCase_ 		=     nn.Convad(UpperCAmelCase       ,	block_out_channels[0]       ,	kernel_size=3       ,	padding=(1, 1)      )

							# time
							if time_embedding_type == "fourier":
										lowerCamelCase_ 		=     GaussianFourierProjection(embedding_size=block_out_channels[0]       ,	scale=16      )
										lowerCamelCase_ 		=     2 * block_out_channels[0]
							elif time_embedding_type == "positional":
										lowerCamelCase_ 		=     Timesteps(block_out_channels[0]       ,	UpperCAmelCase       ,	UpperCAmelCase      )
										lowerCamelCase_ 		=     block_out_channels[0]

							lowerCamelCase_ 		=     TimestepEmbedding(UpperCAmelCase       ,	UpperCAmelCase      )

							# class embedding
							if class_embed_type is None and num_class_embeds is not None:
										lowerCamelCase_ 		=     nn.Embedding(UpperCAmelCase       ,	UpperCAmelCase      )
							elif class_embed_type == "timestep":
										lowerCamelCase_ 		=     TimestepEmbedding(UpperCAmelCase       ,	UpperCAmelCase      )
							elif class_embed_type == "identity":
										lowerCamelCase_ 		=     nn.Identity(UpperCAmelCase       ,	UpperCAmelCase      )
							else:
										lowerCamelCase_ 		=     None

							lowerCamelCase_ 		=     nn.ModuleList([]      )
							lowerCamelCase_ 		=     None
							lowerCamelCase_ 		=     nn.ModuleList([]      )

							# down
							lowerCamelCase_ 		=     block_out_channels[0]
							for i, down_block_type in enumerate(UpperCAmelCase      ):
										lowerCamelCase_ 		=     output_channel
										lowerCamelCase_ 		=     block_out_channels[i]
										lowerCamelCase_ 		=     i == len(UpperCAmelCase      ) - 1

										lowerCamelCase_ 		=     get_down_block(
										    UpperCAmelCase       ,	num_layers=UpperCAmelCase       ,	in_channels=UpperCAmelCase       ,	out_channels=UpperCAmelCase       ,	temb_channels=UpperCAmelCase       ,	add_downsample=not is_final_block       ,	resnet_eps=UpperCAmelCase       ,	resnet_act_fn=UpperCAmelCase       ,	resnet_groups=UpperCAmelCase       ,	attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel       ,	downsample_padding=UpperCAmelCase       ,	resnet_time_scale_shift=UpperCAmelCase       ,	downsample_type=UpperCAmelCase       ,	)
										self.down_blocks.append(UpperCAmelCase      )

							# mid
							lowerCamelCase_ 		=     UNetMidBlockaD(
							    in_channels=block_out_channels[-1]       ,	temb_channels=UpperCAmelCase       ,	resnet_eps=UpperCAmelCase       ,	resnet_act_fn=UpperCAmelCase       ,	output_scale_factor=UpperCAmelCase       ,	resnet_time_scale_shift=UpperCAmelCase       ,	attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1]       ,	resnet_groups=UpperCAmelCase       ,	add_attention=UpperCAmelCase       ,	)

							# up
							lowerCamelCase_ 		=     list(reversed(UpperCAmelCase      )      )
							lowerCamelCase_ 		=     reversed_block_out_channels[0]
							for i, up_block_type in enumerate(UpperCAmelCase      ):
										lowerCamelCase_ 		=     output_channel
										lowerCamelCase_ 		=     reversed_block_out_channels[i]
										lowerCamelCase_ 		=     reversed_block_out_channels[min(i + 1       ,	len(UpperCAmelCase      ) - 1      )]

										lowerCamelCase_ 		=     i == len(UpperCAmelCase      ) - 1

										lowerCamelCase_ 		=     get_up_block(
										    UpperCAmelCase       ,	num_layers=layers_per_block + 1       ,	in_channels=UpperCAmelCase       ,	out_channels=UpperCAmelCase       ,	prev_output_channel=UpperCAmelCase       ,	temb_channels=UpperCAmelCase       ,	add_upsample=not is_final_block       ,	resnet_eps=UpperCAmelCase       ,	resnet_act_fn=UpperCAmelCase       ,	resnet_groups=UpperCAmelCase       ,	attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel       ,	resnet_time_scale_shift=UpperCAmelCase       ,	upsample_type=UpperCAmelCase       ,	)
										self.up_blocks.append(UpperCAmelCase      )
										lowerCamelCase_ 		=     output_channel

							# out
							lowerCamelCase_ 		=     norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4       ,	32      )
							lowerCamelCase_ 		=     nn.GroupNorm(num_channels=block_out_channels[0]       ,	num_groups=UpperCAmelCase       ,	eps=UpperCAmelCase      )
							lowerCamelCase_ 		=     nn.SiLU()
							lowerCamelCase_ 		=     nn.Convad(block_out_channels[0]       ,	UpperCAmelCase       ,	kernel_size=3       ,	padding=1      )





				def 					UpperCAmelCase__	(							self       ,	UpperCAmelCase       ,	UpperCAmelCase       ,	UpperCAmelCase = None       ,	UpperCAmelCase = True       ,	):
							# 0. center input if necessary
							if self.config.center_input_sample:
										lowerCamelCase_ 		=     2 * sample - 1.0

							# 1. time
							lowerCamelCase_ 		=     timestep
							if not torch.is_tensor(UpperCAmelCase      ):
										lowerCamelCase_ 		=     torch.tensor([timesteps]       ,	dtype=torch.long       ,	device=sample.device      )
							elif torch.is_tensor(UpperCAmelCase      ) and len(timesteps.shape      ) == 0:
										lowerCamelCase_ 		=     timesteps[None].to(sample.device      )

							# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
							lowerCamelCase_ 		=     timesteps * torch.ones(sample.shape[0]       ,	dtype=timesteps.dtype       ,	device=timesteps.device      )

							lowerCamelCase_ 		=     self.time_proj(UpperCAmelCase      )

							# timesteps does not contain any weights and will always return f32 tensors
							# but time_embedding might actually be running in fp16. so we need to cast here.
							# there might be better ways to encapsulate this.
							lowerCamelCase_ 		=     t_emb.to(dtype=self.dtype      )
							lowerCamelCase_ 		=     self.time_embedding(UpperCAmelCase      )

							if self.class_embedding is not None:
										if class_labels is None:
													raise ValueError('''class_labels should be provided when doing class conditioning'''      )

										if self.config.class_embed_type == "timestep":
													lowerCamelCase_ 		=     self.time_proj(UpperCAmelCase      )

										lowerCamelCase_ 		=     self.class_embedding(UpperCAmelCase      ).to(dtype=self.dtype      )
										lowerCamelCase_ 		=     emb + class_emb

							# 2. pre-process
							lowerCamelCase_ 		=     sample
							lowerCamelCase_ 		=     self.conv_in(UpperCAmelCase      )

							# 3. down
							lowerCamelCase_ 		=     (sample,)
							for downsample_block in self.down_blocks:
										if hasattr(UpperCAmelCase       ,	'''skip_conv'''      ):
													lowerCamelCase_		,   lowerCamelCase_		,   lowerCamelCase_ 		=     downsample_block(
													    hidden_states=UpperCAmelCase       ,	temb=UpperCAmelCase       ,	skip_sample=UpperCAmelCase      )
										else:
													lowerCamelCase_		,   lowerCamelCase_ 		=     downsample_block(hidden_states=UpperCAmelCase       ,	temb=UpperCAmelCase      )

										down_block_res_samples += res_samples

							# 4. mid
							lowerCamelCase_ 		=     self.mid_block(UpperCAmelCase       ,	UpperCAmelCase      )

							# 5. up
							lowerCamelCase_ 		=     None
							for upsample_block in self.up_blocks:
										lowerCamelCase_ 		=     down_block_res_samples[-len(upsample_block.resnets      ) :]
										lowerCamelCase_ 		=     down_block_res_samples[: -len(upsample_block.resnets      )]

										if hasattr(UpperCAmelCase       ,	'''skip_conv'''      ):
													lowerCamelCase_		,   lowerCamelCase_ 		=     upsample_block(UpperCAmelCase       ,	UpperCAmelCase       ,	UpperCAmelCase       ,	UpperCAmelCase      )
										else:
													lowerCamelCase_ 		=     upsample_block(UpperCAmelCase       ,	UpperCAmelCase       ,	UpperCAmelCase      )

        # 6. post-process
							lowerCamelCase_ 		=     self.conv_norm_out(UpperCAmelCase      )
							lowerCamelCase_ 		=     self.conv_act(UpperCAmelCase      )
							lowerCamelCase_ 		=     self.conv_out(UpperCAmelCase      )

							if skip_sample is not None:
										sample += skip_sample

							if self.config.time_embedding_type == "fourier":
										lowerCamelCase_ 		=     timesteps.reshape((sample.shape[0], *([1] * len(sample.shape[1:]      )))      )
										lowerCamelCase_ 		=     sample / timesteps

							if not return_dict:
										return (sample,)

							return UNetaDOutput(sample=UpperCAmelCase      )





"""simple docstring"""


import copy

from transformers.configuration_utils import PretrainedConfig
from transformers.utils import logging


A_						       =				logging.get_logger(__name__)




class    __lowerCamelCase     (   lowerCAmelCase ):
				a__:			List[str]									=						'hybrid-clip'
				a__:			List[Any]									=						True




				def __init__(							self       ,	UpperCAmelCase=512       ,	**UpperCAmelCase      ):
							super().__init__(**UpperCAmelCase      )

							if "text_config" not in kwargs:
										raise ValueError('''`text_config` can not be `None`.'''      )

							if "vision_config" not in kwargs:
										raise ValueError('''`vision_config` can not be `None`.'''      )

							lowerCamelCase_ 		=     kwargs.pop('''text_config'''      )
							lowerCamelCase_ 		=     kwargs.pop('''vision_config'''      )

							lowerCamelCase_ 		=     text_config.pop('''model_type'''      )
							lowerCamelCase_ 		=     vision_config.pop('''model_type'''      )

							from transformers import AutoConfig

							lowerCamelCase_ 		=     AutoConfig.for_model(UpperCAmelCase       ,	**UpperCAmelCase      )

							if vision_model_type == "clip":
										lowerCamelCase_ 		=     AutoConfig.for_model(UpperCAmelCase       ,	**UpperCAmelCase      ).vision_config
							elif vision_model_type == "clip_vision_model":
										from transformers import CLIPVisionConfig

										lowerCamelCase_ 		=     CLIPVisionConfig(**UpperCAmelCase      )
							else:
										lowerCamelCase_ 		=     AutoConfig.for_model(UpperCAmelCase       ,	**UpperCAmelCase      )

							lowerCamelCase_ 		=     projection_dim
							lowerCamelCase_ 		=     1.0




				@classmethod
				def 					UpperCAmelCase__	(							cls       ,	UpperCAmelCase       ,	UpperCAmelCase       ,	**UpperCAmelCase      ):
							return cls(text_config=text_config.to_dict()       ,	vision_config=vision_config.to_dict()       ,	**UpperCAmelCase      )





				def 					UpperCAmelCase__	(							self      ):
							lowerCamelCase_ 		=     copy.deepcopy(self.__dict__      )
							lowerCamelCase_ 		=     self.text_config.to_dict()
							lowerCamelCase_ 		=     self.vision_config.to_dict()
							lowerCamelCase_ 		=     self.__class__.model_type
							return output



