

'''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 							_snake_case (       _a						):
   _A       :     torch.FloatTensor





class 							_snake_case (       _a	,  _a						):
   @register_to_config
   def __init__( self			:      Optional[int]     ,SCREAMING_SNAKE_CASE__			:      int = 32     ,SCREAMING_SNAKE_CASE__			:      int = 64     ,SCREAMING_SNAKE_CASE__			:      int = 20     ,SCREAMING_SNAKE_CASE__			:      int = 768     ,SCREAMING_SNAKE_CASE__			:      Optional[Any]=77     ,SCREAMING_SNAKE_CASE__			:      Any=4     ,SCREAMING_SNAKE_CASE__			:      float = 0.0     ,SCREAMING_SNAKE_CASE__			:      str = "silu"     ,SCREAMING_SNAKE_CASE__			:      Optional[str] = None     ,SCREAMING_SNAKE_CASE__			:      Optional[str] = None     ,SCREAMING_SNAKE_CASE__			:      Optional[str] = "linear"     ,SCREAMING_SNAKE_CASE__			:      Optional[str] = "prd"     ,SCREAMING_SNAKE_CASE__			:      Optional[int] = None     ,SCREAMING_SNAKE_CASE__			:      Optional[int] = None     ,SCREAMING_SNAKE_CASE__			:      Optional[int] = None     ,):
     super().__init__()
     SCREAMING_SNAKE_CASE:Any						      =					num_attention_heads
     SCREAMING_SNAKE_CASE:List[str]						      =					attention_head_dim
     SCREAMING_SNAKE_CASE:List[str]						      =					num_attention_heads * attention_head_dim
     SCREAMING_SNAKE_CASE:Optional[Any]						      =					additional_embeddings

     SCREAMING_SNAKE_CASE:Optional[int]						      =					time_embed_dim or inner_dim
     SCREAMING_SNAKE_CASE:Optional[int]						      =					embedding_proj_dim or embedding_dim
     SCREAMING_SNAKE_CASE:Any						      =					clip_embed_dim or embedding_dim

     SCREAMING_SNAKE_CASE:Any						      =					Timesteps(SCREAMING_SNAKE_CASE__     ,SCREAMING_SNAKE_CASE__     ,0							)
     SCREAMING_SNAKE_CASE:int						      =					TimestepEmbedding(SCREAMING_SNAKE_CASE__     ,SCREAMING_SNAKE_CASE__     ,out_dim=SCREAMING_SNAKE_CASE__     ,act_fn=SCREAMING_SNAKE_CASE__							)

     SCREAMING_SNAKE_CASE:List[str]						      =					nn.Linear(SCREAMING_SNAKE_CASE__     ,SCREAMING_SNAKE_CASE__							)

     if embedding_proj_norm_type is None:
       SCREAMING_SNAKE_CASE:Union[str, Any]						      =					None
     elif embedding_proj_norm_type == "layer":
       SCREAMING_SNAKE_CASE:List[Any]						      =					nn.LayerNorm(SCREAMING_SNAKE_CASE__							)
     else:
       raise ValueError(F'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}'''							)

     SCREAMING_SNAKE_CASE:Union[str, Any]						      =					nn.Linear(SCREAMING_SNAKE_CASE__     ,SCREAMING_SNAKE_CASE__							)

     if encoder_hid_proj_type is None:
       SCREAMING_SNAKE_CASE:Dict						      =					None
     elif encoder_hid_proj_type == "linear":
       SCREAMING_SNAKE_CASE:Union[str, Any]						      =					nn.Linear(SCREAMING_SNAKE_CASE__     ,SCREAMING_SNAKE_CASE__							)
     else:
       raise ValueError(F'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}'''							)

     SCREAMING_SNAKE_CASE:Optional[Any]						      =					nn.Parameter(torch.zeros(1     ,num_embeddings + additional_embeddings     ,SCREAMING_SNAKE_CASE__							)							)

     if added_emb_type == "prd":
       SCREAMING_SNAKE_CASE:Dict						      =					nn.Parameter(torch.zeros(1     ,1     ,SCREAMING_SNAKE_CASE__							)							)
     elif added_emb_type is None:
       SCREAMING_SNAKE_CASE:Dict						      =					None
     else:
       raise ValueError(
           F'''`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.'''							)

     SCREAMING_SNAKE_CASE:Optional[int]						      =					nn.ModuleList(
         [
             BasicTransformerBlock(
                 SCREAMING_SNAKE_CASE__     ,SCREAMING_SNAKE_CASE__     ,SCREAMING_SNAKE_CASE__     ,dropout=SCREAMING_SNAKE_CASE__     ,activation_fn="gelu"     ,attention_bias=SCREAMING_SNAKE_CASE__     ,)
             for d in range(SCREAMING_SNAKE_CASE__							)
         ]							)

     if norm_in_type == "layer":
       SCREAMING_SNAKE_CASE:Optional[Any]						      =					nn.LayerNorm(SCREAMING_SNAKE_CASE__							)
     elif norm_in_type is None:
       SCREAMING_SNAKE_CASE:str						      =					None
     else:
       raise ValueError(F'''Unsupported norm_in_type: {norm_in_type}.'''							)

     SCREAMING_SNAKE_CASE:Union[str, Any]						      =					nn.LayerNorm(SCREAMING_SNAKE_CASE__							)

     SCREAMING_SNAKE_CASE:Union[str, Any]						      =					nn.Linear(SCREAMING_SNAKE_CASE__     ,SCREAMING_SNAKE_CASE__							)

     SCREAMING_SNAKE_CASE:str						      =					torch.full(
         [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings]     ,-10_000.0							)
     causal_attention_mask.triu_(1							)
     SCREAMING_SNAKE_CASE:Dict						      =					causal_attention_mask[None, ...]
     self.register_buffer("causal_attention_mask"     ,SCREAMING_SNAKE_CASE__     ,persistent=SCREAMING_SNAKE_CASE__							)

     SCREAMING_SNAKE_CASE:Any						      =					nn.Parameter(torch.zeros(1     ,SCREAMING_SNAKE_CASE__							)							)
     SCREAMING_SNAKE_CASE:Optional[Any]						      =					nn.Parameter(torch.zeros(1     ,SCREAMING_SNAKE_CASE__							)							)
   @property
   # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
   def     __UpperCamelCase						( self			:      List[Any]							):
     SCREAMING_SNAKE_CASE:str						      =					{}

     def fn_recursive_add_processors(SCREAMING_SNAKE_CASE__			:      str     ,SCREAMING_SNAKE_CASE__			:      torch.nn.Module     ,SCREAMING_SNAKE_CASE__			:      Dict[str, AttentionProcessor]							):
       if hasattr(SCREAMING_SNAKE_CASE__     ,"set_processor"							):
         SCREAMING_SNAKE_CASE:Any						      =					module.processor

       for sub_name, child in module.named_children():
         fn_recursive_add_processors(F'''{name}.{sub_name}'''     ,SCREAMING_SNAKE_CASE__     ,SCREAMING_SNAKE_CASE__							)

       return processors

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

     return processors
   def     __UpperCamelCase						( self			:      str     ,SCREAMING_SNAKE_CASE__			:      Union[AttentionProcessor, Dict[str, AttentionProcessor]]							):
     SCREAMING_SNAKE_CASE:List[str]						      =					len(self.attn_processors.keys()							)

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

     def fn_recursive_attn_processor(SCREAMING_SNAKE_CASE__			:      str     ,SCREAMING_SNAKE_CASE__			:      torch.nn.Module     ,SCREAMING_SNAKE_CASE__			:      Union[str, Any]							):
       if hasattr(SCREAMING_SNAKE_CASE__     ,"set_processor"							):
         if not isinstance(SCREAMING_SNAKE_CASE__     ,SCREAMING_SNAKE_CASE__							):
           module.set_processor(SCREAMING_SNAKE_CASE__							)
         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}'''     ,SCREAMING_SNAKE_CASE__     ,SCREAMING_SNAKE_CASE__							)

     for name, module in self.named_children():
       fn_recursive_attn_processor(SCREAMING_SNAKE_CASE__     ,SCREAMING_SNAKE_CASE__     ,SCREAMING_SNAKE_CASE__							)
   def     __UpperCamelCase						( self			:      List[Any]							):
     self.set_attn_processor(AttnProcessor()							)
   def     __UpperCamelCase						( self			:      int     ,SCREAMING_SNAKE_CASE__			:      Tuple     ,SCREAMING_SNAKE_CASE__			:      Union[torch.Tensor, float, int]     ,SCREAMING_SNAKE_CASE__			:      torch.FloatTensor     ,SCREAMING_SNAKE_CASE__			:      Optional[torch.FloatTensor] = None     ,SCREAMING_SNAKE_CASE__			:      Optional[torch.BoolTensor] = None     ,SCREAMING_SNAKE_CASE__			:      bool = True     ,):
     SCREAMING_SNAKE_CASE:int						      =					hidden_states.shape[0]

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

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

     SCREAMING_SNAKE_CASE:Optional[int]						      =					self.time_proj(SCREAMING_SNAKE_CASE__							)

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

     if self.embedding_proj_norm is not None:
       SCREAMING_SNAKE_CASE:List[str]						      =					self.embedding_proj_norm(SCREAMING_SNAKE_CASE__							)

     SCREAMING_SNAKE_CASE:Optional[int]						      =					self.embedding_proj(SCREAMING_SNAKE_CASE__							)
     if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
       SCREAMING_SNAKE_CASE:int						      =					self.encoder_hidden_states_proj(SCREAMING_SNAKE_CASE__							)
     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"							)

     SCREAMING_SNAKE_CASE:List[str]						      =					self.proj_in(SCREAMING_SNAKE_CASE__							)

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

     SCREAMING_SNAKE_CASE:Optional[Any]						      =					[]
     SCREAMING_SNAKE_CASE:Dict						      =					0

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

     if len(proj_embeddings.shape							) == 2:
       SCREAMING_SNAKE_CASE:str						      =					proj_embeddings[:, None, :]

     if len(hidden_states.shape							) == 2:
       SCREAMING_SNAKE_CASE:List[Any]						      =					hidden_states[:, None, :]

     SCREAMING_SNAKE_CASE:str						      =					additional_embeds + [
         proj_embeddings,
         time_embeddings[:, None, :],
         hidden_states,
     ]

     if self.prd_embedding is not None:
       SCREAMING_SNAKE_CASE:List[Any]						      =					self.prd_embedding.to(hidden_states.dtype							).expand(SCREAMING_SNAKE_CASE__     ,-1     ,-1							)
       additional_embeds.append(SCREAMING_SNAKE_CASE__							)

     SCREAMING_SNAKE_CASE:int						      =					torch.cat(
         SCREAMING_SNAKE_CASE__     ,dim=1     ,)

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

     SCREAMING_SNAKE_CASE:Tuple						      =					hidden_states + positional_embeddings

     if attention_mask is not None:
       SCREAMING_SNAKE_CASE:str						      =					(1 - attention_mask.to(hidden_states.dtype							)) * -10_000.0
       SCREAMING_SNAKE_CASE:Any						      =					F.pad(SCREAMING_SNAKE_CASE__     ,(0, self.additional_embeddings)     ,value=0.0							)
       SCREAMING_SNAKE_CASE:Optional[Any]						      =					(attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype							)
       SCREAMING_SNAKE_CASE:str						      =					attention_mask.repeat_interleave(self.config.num_attention_heads     ,dim=0							)

     if self.norm_in is not None:
       SCREAMING_SNAKE_CASE:int						      =					self.norm_in(SCREAMING_SNAKE_CASE__							)

     for block in self.transformer_blocks:
       SCREAMING_SNAKE_CASE:Dict						      =					block(SCREAMING_SNAKE_CASE__     ,attention_mask=SCREAMING_SNAKE_CASE__							)

     SCREAMING_SNAKE_CASE:Optional[Any]						      =					self.norm_out(SCREAMING_SNAKE_CASE__							)

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

     SCREAMING_SNAKE_CASE:Union[str, Any]						      =					self.proj_to_clip_embeddings(SCREAMING_SNAKE_CASE__							)

     if not return_dict:
       return (predicted_image_embedding,)

     return PriorTransformerOutput(predicted_image_embedding=SCREAMING_SNAKE_CASE__							)







   def     __UpperCamelCase						( self			:      Optional[int]     ,SCREAMING_SNAKE_CASE__			:      int							):
     SCREAMING_SNAKE_CASE:str						      =					(prior_latents * self.clip_std) + self.clip_mean
     return prior_latents









'''simple docstring'''

def    A_  ( snake_case = 100 ):
  SCREAMING_SNAKE_CASE:Dict						      =					0
  SCREAMING_SNAKE_CASE:Optional[int]						      =					0
  for i in range(1      ,       n + 1 ):
    sum_of_squares += i**2
    sum_of_ints += i
  return sum_of_ints**2 - sum_of_squares


if __name__ == "__main__":
    print(f'''{solution() = }''')






