'''simple docstring'''




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

import torch
import torch.nn.functional as F
from torch import nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .attention import BasicTransformerBlock
from .attention_processor import AttentionProcessor, AttnProcessor
from .embeddings import TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin






@dataclass
class 		__A       (UpperCamelCase_   ):
       snake_case       :Optional[Any]				    =					42






class 		__A       (UpperCamelCase_ ,					UpperCamelCase_   ):






       @register_to_config
       def __init__(      self				,     UpperCamelCase_ = 32				,     UpperCamelCase_ = 64				,     UpperCamelCase_ = 20				,     UpperCamelCase_ = 7_68				,     UpperCamelCase_=77				,     UpperCamelCase_=4				,     UpperCamelCase_ = 0.0				,     UpperCamelCase_ = "silu"				,     UpperCamelCase_ = None				,     UpperCamelCase_ = None				,     UpperCamelCase_ = "linear"				,     UpperCamelCase_ = "prd"				,     UpperCamelCase_ = None				,     UpperCamelCase_ = None				,     UpperCamelCase_ = None				,     ):
              super().__init__()
              __UpperCAmelCase  :				Dict       				=		num_attention_heads
              __UpperCAmelCase  :				Any       				=		attention_head_dim
              __UpperCAmelCase  :				Union[str, Any]       				=		num_attention_heads * attention_head_dim
              __UpperCAmelCase  :				Optional[Any]       				=		additional_embeddings

              __UpperCAmelCase  :				Tuple       				=		time_embed_dim or inner_dim
              __UpperCAmelCase  :				Optional[int]       				=		embedding_proj_dim or embedding_dim
              __UpperCAmelCase  :				Dict       				=		clip_embed_dim or embedding_dim

              __UpperCAmelCase  :				List[Any]       				=		Timesteps(__A				,     __A				,     0      )
              __UpperCAmelCase  :				int       				=		TimestepEmbedding(__A				,     __A				,     out_dim=__A				,     act_fn=__A      )

              __UpperCAmelCase  :				List[str]       				=		nn.Linear(__A				,     __A      )

              if embedding_proj_norm_type is None:
                     __UpperCAmelCase  :				int       				=		None
              elif embedding_proj_norm_type == "layer":
                     __UpperCAmelCase  :				int       				=		nn.LayerNorm(__A      )
              else:
                     raise ValueError(f"""unsupported embedding_proj_norm_type: {embedding_proj_norm_type}"""      )

              __UpperCAmelCase  :				List[str]       				=		nn.Linear(__A				,     __A      )

              if encoder_hid_proj_type is None:
                     __UpperCAmelCase  :				str       				=		None
              elif encoder_hid_proj_type == "linear":
                     __UpperCAmelCase  :				Optional[Any]       				=		nn.Linear(__A				,     __A      )
              else:
                     raise ValueError(f"""unsupported encoder_hid_proj_type: {encoder_hid_proj_type}"""      )

              __UpperCAmelCase  :				Any       				=		nn.Parameter(torch.zeros(1				,     num_embeddings + additional_embeddings				,     __A      )      )

              if added_emb_type == "prd":
                     __UpperCAmelCase  :				int       				=		nn.Parameter(torch.zeros(1				,     1				,     __A      )      )
              elif added_emb_type is None:
                     __UpperCAmelCase  :				Tuple       				=		None
              else:
                     raise ValueError(
                         f"""`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`."""      )

              __UpperCAmelCase  :				List[str]       				=		nn.ModuleList(
                  [
                      BasicTransformerBlock(
                          __A				,     __A				,     __A				,     dropout=__A				,     activation_fn="gelu"				,     attention_bias=__A				,     )
                      for d in range(__A      )
                  ]      )

              if norm_in_type == "layer":
                     __UpperCAmelCase  :				Any       				=		nn.LayerNorm(__A      )
              elif norm_in_type is None:
                     __UpperCAmelCase  :				str       				=		None
              else:
                     raise ValueError(f"""Unsupported norm_in_type: {norm_in_type}."""      )

              __UpperCAmelCase  :				Optional[int]       				=		nn.LayerNorm(__A      )

              __UpperCAmelCase  :				Optional[Any]       				=		nn.Linear(__A				,     __A      )

              __UpperCAmelCase  :				Optional[Any]       				=		torch.full(
                  [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings]				,     -1_00_00.0      )
              causal_attention_mask.triu_(1      )
              __UpperCAmelCase  :				int       				=		causal_attention_mask[None, ...]
              self.register_buffer("causal_attention_mask"				,     __A				,     persistent=__A      )

              __UpperCAmelCase  :				Tuple       				=		nn.Parameter(torch.zeros(1				,     __A      )      )
              __UpperCAmelCase  :				Union[str, Any]       				=		nn.Parameter(torch.zeros(1				,     __A      )      )






       @property
       # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
       def 			_snake_case						(      self      ):
              __UpperCAmelCase  :				Tuple       				=		{}

              def fn_recursive_add_processors(UpperCamelCase_				,     UpperCamelCase_				,     UpperCamelCase_      ):
                     if hasattr(__A				,     "set_processor"      ):
                            __UpperCAmelCase  :				List[str]       				=		module.processor

                     for sub_name, child in module.named_children():
                            fn_recursive_add_processors(f"""{name}.{sub_name}"""				,     __A				,     __A      )

                     return processors

              for name, module in self.named_children():
                     fn_recursive_add_processors(__A				,     __A				,     __A      )

              return processors






       def 			_snake_case						(      self				,     UpperCamelCase_      ):
              __UpperCAmelCase  :				int       				=		len(self.attn_processors.keys()      )

              if isinstance(__A				,     __A      ) and len(__A      ) != count:
                     raise ValueError(
                         f"""A dict of processors was passed, but the number of processors {len(__A      )} does not match the"""
                         f""" number of attention layers: {count}. Please make sure to pass {count} processor classes."""      )

              def fn_recursive_attn_processor(UpperCamelCase_				,     UpperCamelCase_				,     UpperCamelCase_      ):
                     if hasattr(__A				,     "set_processor"      ):
                            if not isinstance(__A				,     __A      ):
                                   module.set_processor(__A      )
                            else:
                                   module.set_processor(processor.pop(f"""{name}.processor"""      )      )

                     for sub_name, child in module.named_children():
                            fn_recursive_attn_processor(f"""{name}.{sub_name}"""				,     __A				,     __A      )

              for name, module in self.named_children():
                     fn_recursive_attn_processor(__A				,     __A				,     __A      )






       def 			_snake_case						(      self      ):
              self.set_attn_processor(AttnProcessor()      )






       def 			_snake_case						(      self				,     UpperCamelCase_				,     UpperCamelCase_				,     UpperCamelCase_				,     UpperCamelCase_ = None				,     UpperCamelCase_ = None				,     UpperCamelCase_ = True				,     ):
              __UpperCAmelCase  :				List[str]       				=		hidden_states.shape[0]

              __UpperCAmelCase  :				int       				=		timestep
              if not torch.is_tensor(__A      ):
                     __UpperCAmelCase  :				Dict       				=		torch.tensor([timesteps]				,     dtype=torch.long				,     device=hidden_states.device      )
              elif torch.is_tensor(__A      ) and len(timesteps.shape      ) == 0:
                     __UpperCAmelCase  :				Union[str, Any]       				=		timesteps[None].to(hidden_states.device      )

              # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
              __UpperCAmelCase  :				Optional[Any]       				=		timesteps * torch.ones(__A				,     dtype=timesteps.dtype				,     device=timesteps.device      )

              __UpperCAmelCase  :				Any       				=		self.time_proj(__A      )

              # timesteps does not contain any weights and will always return f32 tensors
              # but time_embedding might be fp16, so we need to cast here.
              __UpperCAmelCase  :				int       				=		timesteps_projected.to(dtype=self.dtype      )
              __UpperCAmelCase  :				List[str]       				=		self.time_embedding(__A      )

              if self.embedding_proj_norm is not None:
                     __UpperCAmelCase  :				List[str]       				=		self.embedding_proj_norm(__A      )

              __UpperCAmelCase  :				str       				=		self.embedding_proj(__A      )
              if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
                     __UpperCAmelCase  :				Any       				=		self.encoder_hidden_states_proj(__A      )
              elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None:
                     raise ValueError("`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set"      )

              __UpperCAmelCase  :				List[str]       				=		self.proj_in(__A      )

              __UpperCAmelCase  :				Union[str, Any]       				=		self.positional_embedding.to(hidden_states.dtype      )

              __UpperCAmelCase  :				Optional[int]       				=		[]
              __UpperCAmelCase  :				Dict       				=		0

              if encoder_hidden_states is not None:
                     additional_embeds.append(__A      )
                     additional_embeddings_len += encoder_hidden_states.shape[1]

              if len(proj_embeddings.shape      ) == 2:
                     __UpperCAmelCase  :				Tuple       				=		proj_embeddings[:, None, :]

              if len(hidden_states.shape      ) == 2:
                     __UpperCAmelCase  :				Dict       				=		hidden_states[:, None, :]

              __UpperCAmelCase  :				Any       				=		additional_embeds + [
                  proj_embeddings,
                  time_embeddings[:, None, :],
                  hidden_states,
              ]

              if self.prd_embedding is not None:
                     __UpperCAmelCase  :				Any       				=		self.prd_embedding.to(hidden_states.dtype      ).expand(__A				,     -1				,     -1      )
                     additional_embeds.append(__A      )

              __UpperCAmelCase  :				Dict       				=		torch.cat(
                  __A				,     dim=1				,     )

              # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens
              __UpperCAmelCase  :				List[Any]       				=		additional_embeddings_len + proj_embeddings.shape[1] + 1
              if positional_embeddings.shape[1] < hidden_states.shape[1]:
                     __UpperCAmelCase  :				Union[str, Any]       				=		F.pad(
                         __A				,     (
                             0,
                             0,
                             additional_embeddings_len,
                             self.prd_embedding.shape[1] if self.prd_embedding is not None else 0,
                         )				,     value=0.0				,     )

              __UpperCAmelCase  :				List[Any]       				=		hidden_states + positional_embeddings

              if attention_mask is not None:
                     __UpperCAmelCase  :				Any       				=		(1 - attention_mask.to(hidden_states.dtype      )) * -1_00_00.0
                     __UpperCAmelCase  :				Tuple       				=		F.pad(__A				,     (0, self.additional_embeddings)				,     value=0.0      )
                     __UpperCAmelCase  :				Dict       				=		(attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype      )
                     __UpperCAmelCase  :				List[str]       				=		attention_mask.repeat_interleave(self.config.num_attention_heads				,     dim=0      )

              if self.norm_in is not None:
                     __UpperCAmelCase  :				Optional[int]       				=		self.norm_in(__A      )

              for block in self.transformer_blocks:
                     __UpperCAmelCase  :				Union[str, Any]       				=		block(__A				,     attention_mask=__A      )

              __UpperCAmelCase  :				Optional[int]       				=		self.norm_out(__A      )

              if self.prd_embedding is not None:
                     __UpperCAmelCase  :				Dict       				=		hidden_states[:, -1]
              else:
                     __UpperCAmelCase  :				Optional[int]       				=		hidden_states[:, additional_embeddings_len:]

              __UpperCAmelCase  :				Union[str, Any]       				=		self.proj_to_clip_embeddings(__A      )

              if not return_dict:
                     return (predicted_image_embedding,)

              return PriorTransformerOutput(predicted_image_embedding=__A      )







       def 			_snake_case						(      self				,     UpperCamelCase_      ):
              __UpperCAmelCase  :				List[str]       				=		(prior_latents * self.clip_std) + self.clip_mean
              return prior_latents







'''simple docstring'''




def _lowercase	(      lowerCamelCase__							,    lowerCamelCase__						)					->       List[str]:





       """simple docstring"""


       __UpperCAmelCase  :				Dict       				=		(boundary[1] - boundary[0]) / steps
       __UpperCAmelCase  :				Tuple       				=		boundary[0]
       __UpperCAmelCase  :				List[str]       				=		boundary[1]
       __UpperCAmelCase  :				List[Any]       				=		make_points(lowerCamelCase__							,    lowerCamelCase__							,    lowerCamelCase__						)
       __UpperCAmelCase  :				int       				=		0.0
       y += (h / 2.0) * f(lowerCamelCase__						)
       for i in x_i:
              # print(i)
              y += h * f(lowerCamelCase__						)
       y += (h / 2.0) * f(lowerCamelCase__						)
       return y

def _lowercase	(      lowerCamelCase__							,    lowerCamelCase__							,    lowerCamelCase__						)					->       List[Any]:





       """simple docstring"""


       __UpperCAmelCase  :				Optional[Any]       				=		a + h
       while x < (b - h):
              yield x
              __UpperCAmelCase  :				List[str]       				=		x + h

def _lowercase	(      lowerCamelCase__						)					->       Optional[Any]:  # enter your function here





       """simple docstring"""


       __UpperCAmelCase  :				str       				=		(x - 0) * (x - 0)
       return y

def _lowercase	(      )					->       int:





       """simple docstring"""


       __UpperCAmelCase  :				Tuple       				=		0.0  # Lower bound of integration
       __UpperCAmelCase  :				Union[str, Any]       				=		1.0  # Upper bound of integration
       __UpperCAmelCase  :				Union[str, Any]       				=		10.0  # define number of steps or resolution
       __UpperCAmelCase  :				Dict       				=		[a, b]  # define boundary of integration
       __UpperCAmelCase  :				Optional[int]       				=		method_a(lowerCamelCase__							,    lowerCamelCase__						)
       print(f"""y = {y}"""						)


if __name__ == "__main__":
   main()






