






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__ (				lowercase_):

       '''simple docstring'''
       lowerCamelCase				:					torch.FloatTensor




class       snake_case__ (				lowercase_						,     lowercase_):

       '''simple docstring'''



       @register_to_config
       def __init__(				self      ,    a__ = 32      ,    a__ = 64      ,    a__ = 20      ,    a__ = 7_68      ,    a__=77      ,    a__=4      ,    a__ = 0.0      ,    a__ = "silu"      ,    a__ = None      ,    a__ = None      ,    a__ = "linear"      ,    a__ = "prd"      ,    a__ = None      ,    a__ = None      ,    a__ = None      ,    )			->   Any:






            '''simple docstring'''





            super().__init__()
            __snake_case      :List[str] 							=    num_attention_heads
            __snake_case      :List[Any] 							=    attention_head_dim
            __snake_case      :Optional[int] 							=    num_attention_heads * attention_head_dim
            __snake_case      :Optional[int] 							=    additional_embeddings

            __snake_case      :Optional[Any] 							=    time_embed_dim or inner_dim
            __snake_case      :Tuple 							=    embedding_proj_dim or embedding_dim
            __snake_case      :List[str] 							=    clip_embed_dim or embedding_dim

            __snake_case      :Optional[int] 							=    Timesteps(a__      ,    a__      ,    0     )
            __snake_case      :Dict 							=    TimestepEmbedding(a__      ,    a__      ,    out_dim=a__      ,    act_fn=a__     )

            __snake_case      :Union[str, Any] 							=    nn.Linear(a__      ,    a__     )

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

            __snake_case      :Tuple 							=    nn.Linear(a__      ,    a__     )

            if encoder_hid_proj_type is None:
                 __snake_case      :List[Any] 							=    None
            elif encoder_hid_proj_type == "linear":
                 __snake_case      :int 							=    nn.Linear(a__      ,    a__     )
            else:
                 raise ValueError(F'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}'''     )

            __snake_case      :int 							=    nn.Parameter(torch.zeros(1      ,    num_embeddings + additional_embeddings      ,    a__     )     )

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

            __snake_case      :Tuple 							=    nn.ModuleList(
                [
                    BasicTransformerBlock(
                        a__      ,    a__      ,    a__      ,    dropout=a__      ,    activation_fn="""gelu"""      ,    attention_bias=a__      ,    )
                    for d in range(a__     )
                ]     )

            if norm_in_type == "layer":
                 __snake_case      :Any 							=    nn.LayerNorm(a__     )
            elif norm_in_type is None:
                 __snake_case      :str 							=    None
            else:
                 raise ValueError(F'''Unsupported norm_in_type: {norm_in_type}.'''     )

            __snake_case      :int 							=    nn.LayerNorm(a__     )

            __snake_case      :Optional[Any] 							=    nn.Linear(a__      ,    a__     )

            __snake_case      :Any 							=    torch.full(
                [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings]      ,    -1_00_00.0     )
            causal_attention_mask.triu_(1     )
            __snake_case      :Dict 							=    causal_attention_mask[None, ...]
            self.register_buffer("""causal_attention_mask"""      ,    a__      ,    persistent=a__     )

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



       @property
       # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
       def        __lowercase    (				self     )			->   Dict[str, AttentionProcessor]:






            '''simple docstring'''





            __snake_case      :List[Any] 							=    {}

            def fn_recursive_add_processors(a__      ,    a__      ,    a__     ):
                 if hasattr(a__      ,    """set_processor"""     ):
                      __snake_case      :int 							=    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        __lowercase    (				self      ,    a__     )			->   Any:






            '''simple docstring'''





            __snake_case      :str 							=    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(a__      ,    a__      ,    a__     ):
                 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        __lowercase    (				self     )			->   Tuple:






            '''simple docstring'''





            self.set_attn_processor(AttnProcessor()     )



       def        __lowercase    (				self      ,    a__      ,    a__      ,    a__      ,    a__ = None      ,    a__ = None      ,    a__ = True      ,    )			->   List[Any]:






            '''simple docstring'''





            __snake_case      :List[Any] 							=    hidden_states.shape[0]

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

            # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
            __snake_case      :str 							=    timesteps * torch.ones(a__      ,    dtype=timesteps.dtype      ,    device=timesteps.device     )

            __snake_case      :Optional[int] 							=    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.
            __snake_case      :List[str] 							=    timesteps_projected.to(dtype=self.dtype     )
            __snake_case      :Tuple 							=    self.time_embedding(a__     )

            if self.embedding_proj_norm is not None:
                 __snake_case      :Dict 							=    self.embedding_proj_norm(a__     )

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

            __snake_case      :List[str] 							=    self.proj_in(a__     )

            __snake_case      :Any 							=    self.positional_embedding.to(hidden_states.dtype     )

            __snake_case      :Any 							=    []
            __snake_case      :List[Any] 							=    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:
                 __snake_case      :str 							=    proj_embeddings[:, None, :]

            if len(hidden_states.shape     ) == 2:
                 __snake_case      :Optional[Any] 							=    hidden_states[:, None, :]

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

            if self.prd_embedding is not None:
                 __snake_case      :List[str] 							=    self.prd_embedding.to(hidden_states.dtype     ).expand(a__      ,    -1      ,    -1     )
                 additional_embeds.append(a__     )

            __snake_case      :int 							=    torch.cat(
                a__      ,    dim=1      ,    )

            # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens
            __snake_case      :Dict 							=    additional_embeddings_len + proj_embeddings.shape[1] + 1
            if positional_embeddings.shape[1] < hidden_states.shape[1]:
                 __snake_case      :int 							=    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      ,    )

            __snake_case      :Any 							=    hidden_states + positional_embeddings

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

            if self.norm_in is not None:
                 __snake_case      :int 							=    self.norm_in(a__     )

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

            __snake_case      :Optional[Any] 							=    self.norm_out(a__     )

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

            __snake_case      :Tuple 							=    self.proj_to_clip_embeddings(a__     )

            if not return_dict:
                 return (predicted_image_embedding,)

            return PriorTransformerOutput(predicted_image_embedding=a__     )



       def        __lowercase    (				self      ,    a__     )			->   List[Any]:






            '''simple docstring'''





            __snake_case      :str 							=    (prior_latents * self.clip_std) + self.clip_mean
            return prior_latents










# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
     import torch




class       snake_case__ (				TensorFormatter[Mapping, "torch.Tensor", Mapping]):

       '''simple docstring'''



       def __init__(				self      ,    a__=None      ,    **a__     )			->   Tuple:






            '''simple docstring'''





            super().__init__(features=a__     )
            __snake_case      :int 							=    torch_tensor_kwargs
            import torch  # noqa import torch at initialization



       def        __lowercase    (				self      ,    a__     )			->   List[str]:






            '''simple docstring'''





            import torch

            if isinstance(a__      ,    a__     ) and column:
                 if all(
                     isinstance(a__      ,    torch.Tensor     ) and x.shape == column[0].shape and x.dtype == column[0].dtype
                     for x in column     ):
                      return torch.stack(a__     )
            return column



       def        __lowercase    (				self      ,    a__     )			->   Union[str, Any]:






            '''simple docstring'''





            import torch

            if isinstance(a__      ,    (str, bytes, type(a__     ))     ):
                 return value
            elif isinstance(a__      ,    (np.character, np.ndarray)     ) and np.issubdtype(value.dtype      ,    np.character     ):
                 return value.tolist()

            __snake_case      :Optional[int] 							=    {}

            if isinstance(a__      ,    (np.number, np.ndarray)     ) and np.issubdtype(value.dtype      ,    np.integer     ):
                 __snake_case      :List[Any] 							=    {"""dtype""": torch.intaa}
            elif isinstance(a__      ,    (np.number, np.ndarray)     ) and np.issubdtype(value.dtype      ,    np.floating     ):
                 __snake_case      :Tuple 							=    {"""dtype""": torch.floataa}
            elif config.PIL_AVAILABLE and "PIL" in sys.modules:
                 import PIL.Image

                 if isinstance(a__      ,    PIL.Image.Image     ):
                      __snake_case      :Union[str, Any] 							=    np.asarray(a__     )
            return torch.tensor(a__      ,    **{**default_dtype, **self.torch_tensor_kwargs}     )



       def        __lowercase    (				self      ,    a__     )			->   str:






            '''simple docstring'''





            import torch

            # support for torch, tf, jax etc.
            if hasattr(a__      ,    """__array__"""     ) and not isinstance(a__      ,    torch.Tensor     ):
                 __snake_case      :Optional[Any] 							=    data_struct.__array__()
            # support for nested types like struct of list of struct
            if isinstance(a__      ,    np.ndarray     ):
                 if data_struct.dtype == object:  # torch tensors cannot be instantied from an array of objects
                      return self._consolidate([self.recursive_tensorize(a__     ) for substruct in data_struct]     )
            elif isinstance(a__      ,    (list, tuple)     ):
                 return self._consolidate([self.recursive_tensorize(a__     ) for substruct in data_struct]     )
            return self._tensorize(a__     )



       def        __lowercase    (				self      ,    a__     )			->   Union[str, Any]:






            '''simple docstring'''





            return map_nested(self._recursive_tensorize      ,    a__      ,    map_list=a__     )



       def        __lowercase    (				self      ,    a__     )			->   Mapping:






            '''simple docstring'''





            __snake_case      :Tuple 							=    self.numpy_arrow_extractor().extract_row(a__     )
            __snake_case      :Any 							=    self.python_features_decoder.decode_row(a__     )
            return self.recursive_tensorize(a__     )



       def        __lowercase    (				self      ,    a__     )			->   "torch.Tensor":






            '''simple docstring'''





            __snake_case      :List[str] 							=    self.numpy_arrow_extractor().extract_column(a__     )
            __snake_case      :List[Any] 							=    self.python_features_decoder.decode_column(a__      ,    pa_table.column_names[0]     )
            __snake_case      :Optional[Any] 							=    self.recursive_tensorize(a__     )
            __snake_case      :Any 							=    self._consolidate(a__     )
            return column



       def        __lowercase    (				self      ,    a__     )			->   Mapping:






            '''simple docstring'''





            __snake_case      :Optional[int] 							=    self.numpy_arrow_extractor().extract_batch(a__     )
            __snake_case      :Tuple 							=    self.python_features_decoder.decode_batch(a__     )
            __snake_case      :Tuple 							=    self.recursive_tensorize(a__     )
            for column_name in batch:
                 __snake_case      :str 							=    self._consolidate(batch[column_name]     )
            return batch


