




"""simple docstring"""







import tempfile

import torch

from diffusers import (
    DEISMultistepScheduler,
    DPMSolverMultistepScheduler,
    DPMSolverSinglestepScheduler,
    UniPCMultistepScheduler,
)

from .test_schedulers import SchedulerCommonTest

class 				snake_case_			(					lowerCamelCase_			):







   """simple docstring"""




   A_				      =       (UniPCMultistepScheduler,)
   A_				      =       (('''num_inference_steps''', 25),)







   def   UpperCAmelCase__			(		self       ,					**lowerCamelCase_)				->   int:
       UpperCamelCase              =	{
           '''num_train_timesteps''': 1_0_0_0,
           '''beta_start''': 0.0001,
           '''beta_end''': 0.02,
           '''beta_schedule''': '''linear''',
           '''solver_order''': 2,
           '''solver_type''': '''bh2''',
       }

       config.update(**lowerCamelCase_)
       return config







   def   UpperCAmelCase__			(		self       ,					lowerCamelCase_=0       ,					**lowerCamelCase_)				->   int:
       UpperCamelCase              =	dict(self.forward_default_kwargs)
       UpperCamelCase              =	kwargs.pop('''num_inference_steps'''       ,					lowerCamelCase_)
       UpperCamelCase              =	self.dummy_sample
       UpperCamelCase              =	0.1 * sample
       UpperCamelCase              =	[residual + 0.2, residual + 0.15, residual + 0.10]

       for scheduler_class in self.scheduler_classes:
           UpperCamelCase              =	self.get_scheduler_config(**lowerCamelCase_)
           UpperCamelCase              =	scheduler_class(**lowerCamelCase_)
           scheduler.set_timesteps(lowerCamelCase_)
           # copy over dummy past residuals
           UpperCamelCase              =	dummy_past_residuals[: scheduler.config.solver_order]

           with tempfile.TemporaryDirectory() as tmpdirname:
               scheduler.save_config(lowerCamelCase_)
               UpperCamelCase              =	scheduler_class.from_pretrained(lowerCamelCase_)
               new_scheduler.set_timesteps(lowerCamelCase_)
               # copy over dummy past residuals
               UpperCamelCase              =	dummy_past_residuals[: new_scheduler.config.solver_order]

           UpperCamelCase       ,	UpperCamelCase              =	sample, sample
           for t in range(lowerCamelCase_       ,					time_step + scheduler.config.solver_order + 1):
               UpperCamelCase              =	scheduler.step(lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_       ,					**lowerCamelCase_).prev_sample
               UpperCamelCase              =	new_scheduler.step(lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_       ,					**lowerCamelCase_).prev_sample

               assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical"







   def   UpperCAmelCase__			(		self       ,					lowerCamelCase_=0       ,					**lowerCamelCase_)				->   Any:
       UpperCamelCase              =	dict(self.forward_default_kwargs)
       UpperCamelCase              =	kwargs.pop('''num_inference_steps'''       ,					lowerCamelCase_)
       UpperCamelCase              =	self.dummy_sample
       UpperCamelCase              =	0.1 * sample
       UpperCamelCase              =	[residual + 0.2, residual + 0.15, residual + 0.10]

       for scheduler_class in self.scheduler_classes:
           UpperCamelCase              =	self.get_scheduler_config()
           UpperCamelCase              =	scheduler_class(**lowerCamelCase_)
           scheduler.set_timesteps(lowerCamelCase_)

           # copy over dummy past residuals (must be after setting timesteps)
           UpperCamelCase              =	dummy_past_residuals[: scheduler.config.solver_order]

           with tempfile.TemporaryDirectory() as tmpdirname:
               scheduler.save_config(lowerCamelCase_)
               UpperCamelCase              =	scheduler_class.from_pretrained(lowerCamelCase_)
               # copy over dummy past residuals
               new_scheduler.set_timesteps(lowerCamelCase_)

               # copy over dummy past residual (must be after setting timesteps)
               UpperCamelCase              =	dummy_past_residuals[: new_scheduler.config.solver_order]

           UpperCamelCase              =	scheduler.step(lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_       ,					**lowerCamelCase_).prev_sample
           UpperCamelCase              =	new_scheduler.step(lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_       ,					**lowerCamelCase_).prev_sample

           assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical"







   def   UpperCAmelCase__			(		self       ,					lowerCamelCase_=None       ,					**lowerCamelCase_)				->   List[Any]:
       if scheduler is None:
           UpperCamelCase              =	self.scheduler_classes[0]
           UpperCamelCase              =	self.get_scheduler_config(**lowerCamelCase_)
           UpperCamelCase              =	scheduler_class(**lowerCamelCase_)

       UpperCamelCase              =	self.scheduler_classes[0]
       UpperCamelCase              =	self.get_scheduler_config(**lowerCamelCase_)
       UpperCamelCase              =	scheduler_class(**lowerCamelCase_)

       UpperCamelCase              =	1_0
       UpperCamelCase              =	self.dummy_model()
       UpperCamelCase              =	self.dummy_sample_deter
       scheduler.set_timesteps(lowerCamelCase_)

       for i, t in enumerate(scheduler.timesteps):
           UpperCamelCase              =	model(lowerCamelCase_       ,					lowerCamelCase_)
           UpperCamelCase              =	scheduler.step(lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_).prev_sample

       return sample







   def   UpperCAmelCase__			(		self)				->   Optional[Any]:
       UpperCamelCase              =	dict(self.forward_default_kwargs)

       UpperCamelCase              =	kwargs.pop('''num_inference_steps'''       ,					lowerCamelCase_)

       for scheduler_class in self.scheduler_classes:
           UpperCamelCase              =	self.get_scheduler_config()
           UpperCamelCase              =	scheduler_class(**lowerCamelCase_)

           UpperCamelCase              =	self.dummy_sample
           UpperCamelCase              =	0.1 * sample

           if num_inference_steps is not None and hasattr(lowerCamelCase_       ,					'''set_timesteps'''):
               scheduler.set_timesteps(lowerCamelCase_)
           elif num_inference_steps is not None and not hasattr(lowerCamelCase_       ,					'''set_timesteps'''):
               UpperCamelCase              =	num_inference_steps

           # copy over dummy past residuals (must be done after set_timesteps)
           UpperCamelCase              =	[residual + 0.2, residual + 0.15, residual + 0.10]
           UpperCamelCase              =	dummy_past_residuals[: scheduler.config.solver_order]

           UpperCamelCase              =	scheduler.timesteps[5]
           UpperCamelCase              =	scheduler.timesteps[6]

           UpperCamelCase              =	scheduler.step(lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_       ,					**lowerCamelCase_).prev_sample
           UpperCamelCase              =	scheduler.step(lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_       ,					**lowerCamelCase_).prev_sample

           self.assertEqual(output_a.shape       ,					sample.shape)
           self.assertEqual(output_a.shape       ,					output_a.shape)







   def   UpperCAmelCase__			(		self)				->   int:
       # make sure that iterating over schedulers with same config names gives same results
       # for defaults
       UpperCamelCase              =	UniPCMultistepScheduler(**self.get_scheduler_config())
       UpperCamelCase              =	self.full_loop(scheduler=lowerCamelCase_)
       UpperCamelCase              =	torch.mean(torch.abs(lowerCamelCase_))

       assert abs(result_mean.item() - 0.2464) < 1e-3

       UpperCamelCase              =	DPMSolverSinglestepScheduler.from_config(scheduler.config)
       UpperCamelCase              =	DEISMultistepScheduler.from_config(scheduler.config)
       UpperCamelCase              =	DPMSolverMultistepScheduler.from_config(scheduler.config)
       UpperCamelCase              =	UniPCMultistepScheduler.from_config(scheduler.config)

       UpperCamelCase              =	self.full_loop(scheduler=lowerCamelCase_)
       UpperCamelCase              =	torch.mean(torch.abs(lowerCamelCase_))

       assert abs(result_mean.item() - 0.2464) < 1e-3







   def   UpperCAmelCase__			(		self)				->   Optional[Any]:
       for timesteps in [2_5, 5_0, 1_0_0, 9_9_9, 1_0_0_0]:
           self.check_over_configs(num_train_timesteps=lowerCamelCase_)







   def   UpperCAmelCase__			(		self)				->   Optional[Any]:
       self.check_over_configs(thresholding=lowerCamelCase_)
       for order in [1, 2, 3]:
           for solver_type in ["bh1", "bh2"]:
               for threshold in [0.5, 1.0, 2.0]:
                   for prediction_type in ["epsilon", "sample"]:
                       self.check_over_configs(
                           thresholding=lowerCamelCase_       ,					prediction_type=lowerCamelCase_       ,					sample_max_value=lowerCamelCase_       ,					solver_order=lowerCamelCase_       ,					solver_type=lowerCamelCase_       ,					)







   def   UpperCAmelCase__			(		self)				->   Optional[int]:
       for prediction_type in ["epsilon", "v_prediction"]:
           self.check_over_configs(prediction_type=lowerCamelCase_)







   def   UpperCAmelCase__			(		self)				->   Tuple:
       for solver_type in ["bh1", "bh2"]:
           for order in [1, 2, 3]:
               for prediction_type in ["epsilon", "sample"]:
                   self.check_over_configs(
                       solver_order=lowerCamelCase_       ,					solver_type=lowerCamelCase_       ,					prediction_type=lowerCamelCase_       ,					)
                   UpperCamelCase              =	self.full_loop(
                       solver_order=lowerCamelCase_       ,					solver_type=lowerCamelCase_       ,					prediction_type=lowerCamelCase_       ,					)
                   assert not torch.isnan(lowerCamelCase_).any(), "Samples have nan numbers"







   def   UpperCAmelCase__			(		self)				->   Optional[Any]:
       self.check_over_configs(lower_order_final=lowerCamelCase_)
       self.check_over_configs(lower_order_final=lowerCamelCase_)







   def   UpperCAmelCase__			(		self)				->   List[Any]:
       for num_inference_steps in [1, 2, 3, 5, 1_0, 5_0, 1_0_0, 9_9_9, 1_0_0_0]:
           self.check_over_forward(num_inference_steps=lowerCamelCase_       ,					time_step=0)







   def   UpperCAmelCase__			(		self)				->   List[Any]:
       UpperCamelCase              =	self.full_loop()
       UpperCamelCase              =	torch.mean(torch.abs(lowerCamelCase_))

       assert abs(result_mean.item() - 0.2464) < 1e-3







   def   UpperCAmelCase__			(		self)				->   Tuple:
       UpperCamelCase              =	self.full_loop(prediction_type='''v_prediction''')
       UpperCamelCase              =	torch.mean(torch.abs(lowerCamelCase_))

       assert abs(result_mean.item() - 0.1014) < 1e-3







   def   UpperCAmelCase__			(		self)				->   str:
       UpperCamelCase              =	self.scheduler_classes[0]
       UpperCamelCase              =	self.get_scheduler_config(thresholding=lowerCamelCase_       ,					dynamic_thresholding_ratio=0)
       UpperCamelCase              =	scheduler_class(**lowerCamelCase_)

       UpperCamelCase              =	1_0
       UpperCamelCase              =	self.dummy_model()
       UpperCamelCase              =	self.dummy_sample_deter.half()
       scheduler.set_timesteps(lowerCamelCase_)

       for i, t in enumerate(scheduler.timesteps):
           UpperCamelCase              =	model(lowerCamelCase_       ,					lowerCamelCase_)
           UpperCamelCase              =	scheduler.step(lowerCamelCase_       ,					lowerCamelCase_       ,					lowerCamelCase_).prev_sample

       assert sample.dtype == torch.floataa







   def   UpperCAmelCase__			(		self       ,					**lowerCamelCase_)				->   str:
       for scheduler_class in self.scheduler_classes:
           UpperCamelCase              =	self.get_scheduler_config(**lowerCamelCase_)
           UpperCamelCase              =	scheduler_class(**lowerCamelCase_)

           scheduler.set_timesteps(scheduler.config.num_train_timesteps)
           assert len(scheduler.timesteps.unique()) == scheduler.num_inference_steps







"""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		(   __snake_case						):
    SCREAMING_SNAKE_CASE		:	torch.FloatTensor






class 	a		(   __snake_case    , __snake_case						):






    @register_to_config
    def __init__(			self	:				Any			,		__SCREAMING_SNAKE_CASE	:				int = 32			,		__SCREAMING_SNAKE_CASE	:				int = 64			,		__SCREAMING_SNAKE_CASE	:				int = 20			,		__SCREAMING_SNAKE_CASE	:				int = 768			,		__SCREAMING_SNAKE_CASE	:				int=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			,		)	->						List[Any]:
      super().__init__()
      lowerCamelCase_       	=		num_attention_heads
      lowerCamelCase_       	=		attention_head_dim
      lowerCamelCase_       	=		num_attention_heads * attention_head_dim
      lowerCamelCase_       	=		additional_embeddings

      lowerCamelCase_       	=		time_embed_dim or inner_dim
      lowerCamelCase_       	=		embedding_proj_dim or embedding_dim
      lowerCamelCase_       	=		clip_embed_dim or embedding_dim

      lowerCamelCase_       	=		Timesteps(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE			,		0   )
      lowerCamelCase_       	=		TimestepEmbedding(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE			,		out_dim=__SCREAMING_SNAKE_CASE			,		act_fn=__SCREAMING_SNAKE_CASE   )

      lowerCamelCase_       	=		nn.Linear(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   )

      if embedding_proj_norm_type is None:
        lowerCamelCase_       	=		None
      elif embedding_proj_norm_type == "layer":
        lowerCamelCase_       	=		nn.LayerNorm(__SCREAMING_SNAKE_CASE   )
      else:
        raise ValueError(F'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}'''   )

      lowerCamelCase_       	=		nn.Linear(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   )

      if encoder_hid_proj_type is None:
        lowerCamelCase_       	=		None
      elif encoder_hid_proj_type == "linear":
        lowerCamelCase_       	=		nn.Linear(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   )
      else:
        raise ValueError(F'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}'''   )

      lowerCamelCase_       	=		nn.Parameter(torch.zeros(1			,		num_embeddings + additional_embeddings			,		__SCREAMING_SNAKE_CASE   )   )

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

      lowerCamelCase_       	=		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":
        lowerCamelCase_       	=		nn.LayerNorm(__SCREAMING_SNAKE_CASE   )
      elif norm_in_type is None:
        lowerCamelCase_       	=		None
      else:
        raise ValueError(F'''Unsupported norm_in_type: {norm_in_type}.'''   )

      lowerCamelCase_       	=		nn.LayerNorm(__SCREAMING_SNAKE_CASE   )

      lowerCamelCase_       	=		nn.Linear(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   )

      lowerCamelCase_       	=		torch.full(
          [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings]			,		-10_000.0   )
      causal_attention_mask.triu_(1   )
      lowerCamelCase_       	=		causal_attention_mask[None, ...]
      self.register_buffer('causal_attention_mask'			,		__SCREAMING_SNAKE_CASE			,		persistent=__SCREAMING_SNAKE_CASE   )

      lowerCamelCase_       	=		nn.Parameter(torch.zeros(1			,		__SCREAMING_SNAKE_CASE   )   )
      lowerCamelCase_       	=		nn.Parameter(torch.zeros(1			,		__SCREAMING_SNAKE_CASE   )   )






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

      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'   ):
          lowerCamelCase_       	=		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	:				Optional[Any]			,		__SCREAMING_SNAKE_CASE	:				Union[AttentionProcessor, Dict[str, AttentionProcessor]]   )	->						Optional[int]:
      lowerCamelCase_       	=		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	:				str   ):
        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	:				Any   )	->						int:
      self.set_attn_processor(AttnProcessor()   )






    def   UpperCamelCase			(			self	:				str			,		__SCREAMING_SNAKE_CASE	:				Dict			,		__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			,		)	->						List[Any]:
      lowerCamelCase_       	=		hidden_states.shape[0]

      lowerCamelCase_       	=		timestep
      if not torch.is_tensor(__SCREAMING_SNAKE_CASE   ):
        lowerCamelCase_       	=		torch.tensor([timesteps]			,		dtype=torch.long			,		device=hidden_states.device   )
      elif torch.is_tensor(__SCREAMING_SNAKE_CASE   ) and len(timesteps.shape   ) == 0:
        lowerCamelCase_       	=		timesteps[None].to(hidden_states.device   )

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

      lowerCamelCase_       	=		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.
      lowerCamelCase_       	=		timesteps_projected.to(dtype=self.dtype   )
      lowerCamelCase_       	=		self.time_embedding(__SCREAMING_SNAKE_CASE   )

      if self.embedding_proj_norm is not None:
        lowerCamelCase_       	=		self.embedding_proj_norm(__SCREAMING_SNAKE_CASE   )

      lowerCamelCase_       	=		self.embedding_proj(__SCREAMING_SNAKE_CASE   )
      if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
        lowerCamelCase_       	=		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'   )

      lowerCamelCase_       	=		self.proj_in(__SCREAMING_SNAKE_CASE   )

      lowerCamelCase_       	=		self.positional_embedding.to(hidden_states.dtype   )

      lowerCamelCase_       	=		[]
      lowerCamelCase_       	=		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:
        lowerCamelCase_       	=		proj_embeddings[:, None, :]

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

      lowerCamelCase_       	=		additional_embeds + [
          proj_embeddings,
          time_embeddings[:, None, :],
          hidden_states,
      ]

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

      lowerCamelCase_       	=		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
      lowerCamelCase_       	=		additional_embeddings_len + proj_embeddings.shape[1] + 1
      if positional_embeddings.shape[1] < hidden_states.shape[1]:
        lowerCamelCase_       	=		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			,		)

      lowerCamelCase_       	=		hidden_states + positional_embeddings

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

      if self.norm_in is not None:
        lowerCamelCase_       	=		self.norm_in(__SCREAMING_SNAKE_CASE   )

      for block in self.transformer_blocks:
        lowerCamelCase_       	=		block(__SCREAMING_SNAKE_CASE			,		attention_mask=__SCREAMING_SNAKE_CASE   )

      lowerCamelCase_       	=		self.norm_out(__SCREAMING_SNAKE_CASE   )

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

      lowerCamelCase_       	=		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[Any]			,		__SCREAMING_SNAKE_CASE	:				Optional[int]   )	->						Optional[int]:
      lowerCamelCase_       	=		(prior_latents * self.clip_std) + self.clip_mean
      return prior_latents




