


'''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			(  _SCREAMING_SNAKE_CASE):







    """simple docstring"""



    lowercase  					=   42







class   __snake_case			(  _SCREAMING_SNAKE_CASE      ,_SCREAMING_SNAKE_CASE):







    """simple docstring"""



    @register_to_config
    def __init__(  self       :    Dict       ,		lowerCamelCase       :    int = 32       ,		lowerCamelCase       :    int = 64       ,		lowerCamelCase       :    int = 20       ,		lowerCamelCase       :    int = 7_68       ,		lowerCamelCase       :    Optional[int]=77       ,		lowerCamelCase       :    List[Any]=4       ,		lowerCamelCase       :    float = 0.0       ,		lowerCamelCase       :    str = "silu"       ,		lowerCamelCase       :    Optional[str] = None       ,		lowerCamelCase       :    Optional[str] = None       ,		lowerCamelCase       :    Optional[str] = "linear"       ,		lowerCamelCase       :    Optional[str] = "prd"       ,		lowerCamelCase       :    Optional[int] = None       ,		lowerCamelCase       :    Optional[int] = None       ,		lowerCamelCase       :    Optional[int] = None       ,		)  ->    Any:
      super().__init__()
      lowerCAmelCase_     : Optional[int]     =  num_attention_heads
      lowerCAmelCase_     : Optional[int]     =  attention_head_dim
      lowerCAmelCase_     : int     =  num_attention_heads * attention_head_dim
      lowerCAmelCase_     : int     =  additional_embeddings

      lowerCAmelCase_     : int     =  time_embed_dim or inner_dim
      lowerCAmelCase_     : str     =  embedding_proj_dim or embedding_dim
      lowerCAmelCase_     : str     =  clip_embed_dim or embedding_dim

      lowerCAmelCase_     : Dict     =  Timesteps(lowerCamelCase       ,		lowerCamelCase       ,		0						)
      lowerCAmelCase_     : Any     =  TimestepEmbedding(lowerCamelCase       ,		lowerCamelCase       ,		out_dim=lowerCamelCase       ,		act_fn=lowerCamelCase						)

      lowerCAmelCase_     : List[Any]     =  nn.Linear(lowerCamelCase       ,		lowerCamelCase						)

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

      lowerCAmelCase_     : Any     =  nn.Linear(lowerCamelCase       ,		lowerCamelCase						)

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

      lowerCAmelCase_     : Tuple     =  nn.Parameter(torch.zeros(1       ,		num_embeddings + additional_embeddings       ,		lowerCamelCase						)						)

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

      lowerCAmelCase_     : Dict     =  nn.ModuleList(
          [
              BasicTransformerBlock(
                  lowerCamelCase       ,		lowerCamelCase       ,		lowerCamelCase       ,		dropout=lowerCamelCase       ,		activation_fn="""gelu"""       ,		attention_bias=lowerCamelCase       ,		)
              for d in range(lowerCamelCase						)
          ]						)

      if norm_in_type == "layer":
        lowerCAmelCase_     : List[str]     =  nn.LayerNorm(lowerCamelCase						)
      elif norm_in_type is None:
        lowerCAmelCase_     : Tuple     =  None
      else:
        raise ValueError(F'Unsupported norm_in_type: {norm_in_type}.'						)

      lowerCAmelCase_     : List[Any]     =  nn.LayerNorm(lowerCamelCase						)

      lowerCAmelCase_     : List[str]     =  nn.Linear(lowerCamelCase       ,		lowerCamelCase						)

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

      lowerCAmelCase_     : List[str]     =  nn.Parameter(torch.zeros(1       ,		lowerCamelCase						)						)
      lowerCAmelCase_     : Optional[int]     =  nn.Parameter(torch.zeros(1       ,		lowerCamelCase						)						)

    @property
    # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
    def __lowercase  (  self       :    List[str]						)  ->    Dict[str, AttentionProcessor]:
      lowerCAmelCase_     : Union[str, Any]     =  {}

      def fn_recursive_add_processors(lowerCamelCase       :    str       ,		lowerCamelCase       :    torch.nn.Module       ,		lowerCamelCase       :    Dict[str, AttentionProcessor]						):
        if hasattr(lowerCamelCase       ,		"""set_processor"""						):
          lowerCAmelCase_     : List[str]     =  module.processor

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

        return processors

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

      return processors

    def __lowercase  (  self       :    str       ,		lowerCamelCase       :    Union[AttentionProcessor, Dict[str, AttentionProcessor]]						)  ->    str:
      lowerCAmelCase_     : Optional[Any]     =  len(self.attn_processors.keys()						)

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

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

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

    def __lowercase  (  self       :    Dict						)  ->    Union[str, Any]:
      self.set_attn_processor(AttnProcessor()						)

    def __lowercase  (  self       :    str       ,		lowerCamelCase       :    Optional[Any]       ,		lowerCamelCase       :    Union[torch.Tensor, float, int]       ,		lowerCamelCase       :    torch.FloatTensor       ,		lowerCamelCase       :    Optional[torch.FloatTensor] = None       ,		lowerCamelCase       :    Optional[torch.BoolTensor] = None       ,		lowerCamelCase       :    bool = True       ,		)  ->    Union[str, Any]:
      lowerCAmelCase_     : Any     =  hidden_states.shape[0]

      lowerCAmelCase_     : int     =  timestep
      if not torch.is_tensor(lowerCamelCase						):
        lowerCAmelCase_     : Any     =  torch.tensor([timesteps]       ,		dtype=torch.long       ,		device=hidden_states.device						)
      elif torch.is_tensor(lowerCamelCase						) and len(timesteps.shape						) == 0:
        lowerCAmelCase_     : List[Any]     =  timesteps[None].to(hidden_states.device						)

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

      lowerCAmelCase_     : str     =  self.time_proj(lowerCamelCase						)

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

      if self.embedding_proj_norm is not None:
        lowerCAmelCase_     : Any     =  self.embedding_proj_norm(lowerCamelCase						)

      lowerCAmelCase_     : Optional[Any]     =  self.embedding_proj(lowerCamelCase						)
      if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
        lowerCAmelCase_     : List[Any]     =  self.encoder_hidden_states_proj(lowerCamelCase						)
      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"""						)

      lowerCAmelCase_     : int     =  self.proj_in(lowerCamelCase						)

      lowerCAmelCase_     : str     =  self.positional_embedding.to(hidden_states.dtype						)

      lowerCAmelCase_     : Optional[int]     =  []
      lowerCAmelCase_     : Any     =  0

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

      if len(proj_embeddings.shape						) == 2:
        lowerCAmelCase_     : Optional[Any]     =  proj_embeddings[:, None, :]

      if len(hidden_states.shape						) == 2:
        lowerCAmelCase_     : Union[str, Any]     =  hidden_states[:, None, :]

      lowerCAmelCase_     : Dict     =  additional_embeds + [
          proj_embeddings,
          time_embeddings[:, None, :],
          hidden_states,
      ]

      if self.prd_embedding is not None:
        lowerCAmelCase_     : Optional[int]     =  self.prd_embedding.to(hidden_states.dtype						).expand(lowerCamelCase       ,		-1       ,		-1						)
        additional_embeds.append(lowerCamelCase						)

      lowerCAmelCase_     : str     =  torch.cat(
          lowerCamelCase       ,		dim=1       ,		)

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

      lowerCAmelCase_     : Optional[Any]     =  hidden_states + positional_embeddings

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

      if self.norm_in is not None:
        lowerCAmelCase_     : int     =  self.norm_in(lowerCamelCase						)

      for block in self.transformer_blocks:
        lowerCAmelCase_     : List[Any]     =  block(lowerCamelCase       ,		attention_mask=lowerCamelCase						)

      lowerCAmelCase_     : str     =  self.norm_out(lowerCamelCase						)

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

      lowerCAmelCase_     : Dict     =  self.proj_to_clip_embeddings(lowerCamelCase						)

      if not return_dict:
        return (predicted_image_embedding,)

      return PriorTransformerOutput(predicted_image_embedding=lowerCamelCase						)





    def __lowercase  (  self       :    Optional[int]       ,		lowerCamelCase       :    Optional[int]						)  ->    Union[str, Any]:
      lowerCAmelCase_     : Union[str, Any]     =  (prior_latents * self.clip_std) + self.clip_mean
      return prior_latents







'''simple docstring'''






import math







def 							UpperCamelCase_     (       A__   :  float				,       A__   :  float   ):
  '''simple docstring'''





  if initial_intensity < 0:
    raise ValueError("""The value of intensity cannot be negative"""   )
    # handling of negative values of initial intensity
  if angle < 0 or angle > 3_60:
    raise ValueError("""In Malus Law, the angle is in the range 0-360 degrees"""   )
    # handling of values out of allowed range
  return initial_intensity * (math.cos(math.radians(A__   )   ) ** 2)


if __name__ == "__main__":
  import doctest

  doctest.testmod(name="malus_law")



