






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  SCREAMING_SNAKE_CASE			(			lowerCAmelCase					):
     '''simple docstring'''


     UpperCamelCase_							:		torch.FloatTensor





class  SCREAMING_SNAKE_CASE			(			lowerCAmelCase      ,		lowerCAmelCase					):
     '''simple docstring'''


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

            SCREAMING_SNAKE_CASE       :      List[str]							=    time_embed_dim or inner_dim
            SCREAMING_SNAKE_CASE       :      Any							=    embedding_proj_dim or embedding_dim
            SCREAMING_SNAKE_CASE       :      List[Any]							=    clip_embed_dim or embedding_dim

            SCREAMING_SNAKE_CASE       :      int							=    Timesteps(UpperCAmelCase_					, UpperCAmelCase_					, 0      )
            SCREAMING_SNAKE_CASE       :      List[Any]							=    TimestepEmbedding(UpperCAmelCase_					, UpperCAmelCase_					, out_dim=UpperCAmelCase_					, act_fn=UpperCAmelCase_      )

            SCREAMING_SNAKE_CASE       :      int							=    nn.Linear(UpperCAmelCase_					, UpperCAmelCase_      )

            if embedding_proj_norm_type is None:
                   SCREAMING_SNAKE_CASE       :      Optional[int]							=    None
            elif embedding_proj_norm_type == "layer":
                   SCREAMING_SNAKE_CASE       :      Any							=    nn.LayerNorm(UpperCAmelCase_      )
            else:
                   raise ValueError(f'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}'''      )

            SCREAMING_SNAKE_CASE       :      str							=    nn.Linear(UpperCAmelCase_					, UpperCAmelCase_      )

            if encoder_hid_proj_type is None:
                   SCREAMING_SNAKE_CASE       :      Optional[int]							=    None
            elif encoder_hid_proj_type == "linear":
                   SCREAMING_SNAKE_CASE       :      Tuple							=    nn.Linear(UpperCAmelCase_					, UpperCAmelCase_      )
            else:
                   raise ValueError(f'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}'''      )

            SCREAMING_SNAKE_CASE       :      Dict							=    nn.Parameter(torch.zeros(1					, num_embeddings + additional_embeddings					, UpperCAmelCase_      )      )

            if added_emb_type == "prd":
                   SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    nn.Parameter(torch.zeros(1					, 1					, UpperCAmelCase_      )      )
            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       :      Dict							=    nn.ModuleList(
                [
                    BasicTransformerBlock(
                        UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, dropout=UpperCAmelCase_					, activation_fn="gelu"					, attention_bias=UpperCAmelCase_					, )
                    for d in range(UpperCAmelCase_      )
                ]      )

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

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

            SCREAMING_SNAKE_CASE       :      Dict							=    nn.Linear(UpperCAmelCase_					, UpperCAmelCase_      )

            SCREAMING_SNAKE_CASE       :      Any							=    torch.full(
                [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings]					, -1_0000.0      )
            causal_attention_mask.triu_(1      )
            SCREAMING_SNAKE_CASE       :      Tuple							=    causal_attention_mask[None, ...]
            self.register_buffer("causal_attention_mask"					, UpperCAmelCase_					, persistent=UpperCAmelCase_      )

            SCREAMING_SNAKE_CASE       :      Dict							=    nn.Parameter(torch.zeros(1					, UpperCAmelCase_      )      )
            SCREAMING_SNAKE_CASE       :      List[Any]							=    nn.Parameter(torch.zeros(1					, UpperCAmelCase_      )      )


     @property
     # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
     def 				_A       (				self       :	int      ):
            SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    {}

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

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

                   return processors

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

            return processors


     def 				_A       (				self       :	int					, UpperCAmelCase_       :	Union[AttentionProcessor, Dict[str, AttentionProcessor]]      ):
            SCREAMING_SNAKE_CASE       :      str							=    len(self.attn_processors.keys()      )

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

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

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


     def 				_A       (				self       :	Optional[int]      ):
            self.set_attn_processor(AttnProcessor()      )


     def 				_A       (				self       :	int					, UpperCAmelCase_       :	Any					, UpperCAmelCase_       :	Union[torch.Tensor, float, int]					, UpperCAmelCase_       :	torch.FloatTensor					, UpperCAmelCase_       :	Optional[torch.FloatTensor] = None					, UpperCAmelCase_       :	Optional[torch.BoolTensor] = None					, UpperCAmelCase_       :	bool = True					, ):
            SCREAMING_SNAKE_CASE       :      int							=    hidden_states.shape[0]

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

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

            SCREAMING_SNAKE_CASE       :      Dict							=    self.time_proj(UpperCAmelCase_      )

            # 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       :      Dict							=    timesteps_projected.to(dtype=self.dtype      )
            SCREAMING_SNAKE_CASE       :      Dict							=    self.time_embedding(UpperCAmelCase_      )

            if self.embedding_proj_norm is not None:
                   SCREAMING_SNAKE_CASE       :      int							=    self.embedding_proj_norm(UpperCAmelCase_      )

            SCREAMING_SNAKE_CASE       :      Optional[Any]							=    self.embedding_proj(UpperCAmelCase_      )
            if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
                   SCREAMING_SNAKE_CASE       :      List[str]							=    self.encoder_hidden_states_proj(UpperCAmelCase_      )
            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       :      Dict							=    self.proj_in(UpperCAmelCase_      )

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

            SCREAMING_SNAKE_CASE       :      List[str]							=    []
            SCREAMING_SNAKE_CASE       :      Optional[Any]							=    0

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

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

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

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

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

            SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    torch.cat(
                UpperCAmelCase_					, 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       :      str							=    F.pad(
                       UpperCAmelCase_					, (
                           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       :      Optional[int]							=    hidden_states + positional_embeddings

            if attention_mask is not None:
                   SCREAMING_SNAKE_CASE       :      Tuple							=    (1 - attention_mask.to(hidden_states.dtype      )) * -1_0000.0
                   SCREAMING_SNAKE_CASE       :      Dict							=    F.pad(UpperCAmelCase_					, (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       :      Optional[int]							=    attention_mask.repeat_interleave(self.config.num_attention_heads					, dim=0      )

            if self.norm_in is not None:
                   SCREAMING_SNAKE_CASE       :      Optional[int]							=    self.norm_in(UpperCAmelCase_      )

            for block in self.transformer_blocks:
                   SCREAMING_SNAKE_CASE       :      Optional[Any]							=    block(UpperCAmelCase_					, attention_mask=UpperCAmelCase_      )

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

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

            SCREAMING_SNAKE_CASE       :      Optional[Any]							=    self.proj_to_clip_embeddings(UpperCAmelCase_      )

            if not return_dict:
                   return (predicted_image_embedding,)

            return PriorTransformerOutput(predicted_image_embedding=UpperCAmelCase_      )






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














from typing import TYPE_CHECKING

from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


snake_case    				=		{
    """configuration_trajectory_transformer""": [
        """TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """TrajectoryTransformerConfig""",
    ],
}

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   snake_case    				=		[
       """TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""",
       """TrajectoryTransformerModel""",
       """TrajectoryTransformerPreTrainedModel""",
       """load_tf_weights_in_trajectory_transformer""",
   ]


if TYPE_CHECKING:
   from .configuration_trajectory_transformer import (
       TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
       TrajectoryTransformerConfig,
   )

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_trajectory_transformer import (
          TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
          TrajectoryTransformerModel,
          TrajectoryTransformerPreTrainedModel,
          load_tf_weights_in_trajectory_transformer,
      )


else:
   import sys

   snake_case    				=		_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)






