"""simple docstring"""







import unittest

import numpy as np
import timeout_decorator  # noqa

from transformers import BlenderbotSmallConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor


if is_flax_available():
       import os

       # The slow tests are often failing with OOM error on GPU
       # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
       # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
       __SCREAMING_SNAKE_CASE    	="platform"

       import jax
       import jax.numpy as jnp

       from transformers.models.blenderbot_small.modeling_flax_blenderbot_small import (
           FlaxBlenderbotSmallForConditionalGeneration,
           FlaxBlenderbotSmallModel,
           shift_tokens_right,
       )



def 			lowercase__(       __SCREAMING_SNAKE_CASE							:     Optional[Any]     ,			__SCREAMING_SNAKE_CASE							:     List[Any]     ,			__SCREAMING_SNAKE_CASE							:     List[Any]=None     ,			__SCREAMING_SNAKE_CASE							:     Union[str, Any]=None     ,			__SCREAMING_SNAKE_CASE							:     List[Any]=None     ,			__SCREAMING_SNAKE_CASE							:     int=None     ,			__SCREAMING_SNAKE_CASE							:     Any=None     ,			__SCREAMING_SNAKE_CASE							:     Dict=None     ,			):
     if attention_mask is None:
          lowercase_	:				Any													=	np.where(input_ids != config.pad_token_id     ,			1     ,			0      )
     if decoder_attention_mask is None:
          lowercase_	:				str													=	np.where(decoder_input_ids != config.pad_token_id     ,			1     ,			0      )
     if head_mask is None:
          lowercase_	:				Union[str, Any]													=	np.ones((config.encoder_layers, config.encoder_attention_heads)      )
     if decoder_head_mask is None:
          lowercase_	:				Optional[Any]													=	np.ones((config.decoder_layers, config.decoder_attention_heads)      )
     if cross_attn_head_mask is None:
          lowercase_	:				str													=	np.ones((config.decoder_layers, config.decoder_attention_heads)      )
     return {
         "input_ids": input_ids,
         "decoder_input_ids": decoder_input_ids,
         "attention_mask": attention_mask,
         "decoder_attention_mask": attention_mask,
     }







class        UpperCamelCase		:
   def __init__(			self     ,__UpperCamelCase     ,__UpperCamelCase=13     ,__UpperCamelCase=7     ,__UpperCamelCase=True     ,__UpperCamelCase=False     ,__UpperCamelCase=99     ,__UpperCamelCase=16     ,__UpperCamelCase=2     ,__UpperCamelCase=4     ,__UpperCamelCase=4     ,__UpperCamelCase="gelu"     ,__UpperCamelCase=0.1     ,__UpperCamelCase=0.1     ,__UpperCamelCase=32     ,__UpperCamelCase=2     ,__UpperCamelCase=1     ,__UpperCamelCase=0     ,__UpperCamelCase=0.02     ,)	->      Any:


        '''simple docstring'''


        lowercase_	:				Optional[Any]													=	parent
        lowercase_	:				Tuple													=	batch_size
        lowercase_	:				Any													=	seq_length
        lowercase_	:				List[str]													=	is_training
        lowercase_	:				Optional[Any]													=	use_labels
        lowercase_	:				Union[str, Any]													=	vocab_size
        lowercase_	:				int													=	hidden_size
        lowercase_	:				List[str]													=	num_hidden_layers
        lowercase_	:				List[str]													=	num_attention_heads
        lowercase_	:				Tuple													=	intermediate_size
        lowercase_	:				Dict													=	hidden_act
        lowercase_	:				Optional[Any]													=	hidden_dropout_prob
        lowercase_	:				Dict													=	attention_probs_dropout_prob
        lowercase_	:				Optional[int]													=	max_position_embeddings
        lowercase_	:				str													=	eos_token_id
        lowercase_	:				Optional[int]													=	pad_token_id
        lowercase_	:				Tuple													=	bos_token_id
        lowercase_	:				List[Any]													=	initializer_range
   def 			_UpperCAmelCase   (			self			)	->      List[Any]:


        '''simple docstring'''


        lowercase_	:				List[Any]													=	np.clip(ids_tensor([self.batch_size, self.seq_length - 1]     ,self.vocab_size			)     ,3     ,self.vocab_size			)
        lowercase_	:				List[Any]													=	np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1)     ,dtype=np.intaa			))     ,-1			)

        lowercase_	:				List[Any]													=	shift_tokens_right(__UpperCamelCase     ,1     ,2			)

        lowercase_	:				Optional[int]													=	BlenderbotSmallConfig(
            vocab_size=self.vocab_size     ,d_model=self.hidden_size     ,encoder_layers=self.num_hidden_layers     ,decoder_layers=self.num_hidden_layers     ,encoder_attention_heads=self.num_attention_heads     ,decoder_attention_heads=self.num_attention_heads     ,encoder_ffn_dim=self.intermediate_size     ,decoder_ffn_dim=self.intermediate_size     ,dropout=self.hidden_dropout_prob     ,attention_dropout=self.attention_probs_dropout_prob     ,max_position_embeddings=self.max_position_embeddings     ,eos_token_id=self.eos_token_id     ,bos_token_id=self.bos_token_id     ,pad_token_id=self.pad_token_id     ,initializer_range=self.initializer_range     ,use_cache=__UpperCamelCase     ,)
        lowercase_	:				Any													=	prepare_blenderbot_inputs_dict(__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase			)
        return config, inputs_dict
   def 			_UpperCAmelCase   (			self			)	->      Optional[int]:


        '''simple docstring'''


        lowercase_							,  lowercase_	:				List[Any]													=	self.prepare_config_and_inputs()
        return config, inputs_dict
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase			)	->      Dict:


        '''simple docstring'''


        lowercase_	:				Any													=	20
        lowercase_	:				Any													=	model_class_name(__UpperCamelCase			)

        lowercase_	:				Any													=	model.encode(inputs_dict['input_ids']			)

        lowercase_							,  lowercase_	:				str													=	(
            inputs_dict['decoder_input_ids'],
            inputs_dict['decoder_attention_mask'],
        )

        lowercase_	:				Optional[Any]													=	model.init_cache(decoder_input_ids.shape[0]     ,__UpperCamelCase     ,__UpperCamelCase			)
        lowercase_	:				Optional[Any]													=	jnp.ones((decoder_input_ids.shape[0], max_decoder_length)     ,dtype='i4'			)

        lowercase_	:				int													=	jnp.broadcast_to(
            jnp.arange(decoder_input_ids.shape[-1] - 1			)[None, :]     ,(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)     ,)
        lowercase_	:				Union[str, Any]													=	model.decode(
            decoder_input_ids[:, :-1]     ,__UpperCamelCase     ,decoder_attention_mask=__UpperCamelCase     ,past_key_values=__UpperCamelCase     ,decoder_position_ids=__UpperCamelCase     ,)

        lowercase_	:				Union[str, Any]													=	jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]     ,dtype='i4'			)
        lowercase_	:				Optional[Any]													=	model.decode(
            decoder_input_ids[:, -1:]     ,__UpperCamelCase     ,decoder_attention_mask=__UpperCamelCase     ,past_key_values=outputs_cache.past_key_values     ,decoder_position_ids=__UpperCamelCase     ,)

        lowercase_	:				Tuple													=	model.decode(__UpperCamelCase     ,__UpperCamelCase			)

        lowercase_	:				Optional[Any]													=	np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])			)			)
        self.parent.assertTrue(diff < 1e-3     ,msg=f'''Max diff is {diff}'''			)







   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase			)	->      List[Any]:


        '''simple docstring'''


        lowercase_	:				str													=	20
        lowercase_	:				Optional[Any]													=	model_class_name(__UpperCamelCase			)

        lowercase_	:				Tuple													=	model.encode(inputs_dict['input_ids']			)

        lowercase_							,  lowercase_	:				int													=	(
            inputs_dict['decoder_input_ids'],
            inputs_dict['decoder_attention_mask'],
        )

        lowercase_	:				str													=	jnp.concatenate(
            [
                decoder_attention_mask,
                jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])			),
            ]     ,axis=-1     ,)

        lowercase_	:				List[str]													=	model.init_cache(decoder_input_ids.shape[0]     ,__UpperCamelCase     ,__UpperCamelCase			)
        lowercase_	:				int													=	jnp.broadcast_to(
            jnp.arange(decoder_input_ids.shape[-1] - 1			)[None, :]     ,(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)     ,)

        lowercase_	:				Optional[int]													=	model.decode(
            decoder_input_ids[:, :-1]     ,__UpperCamelCase     ,decoder_attention_mask=__UpperCamelCase     ,past_key_values=__UpperCamelCase     ,decoder_position_ids=__UpperCamelCase     ,)
        lowercase_	:				Optional[int]													=	jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]     ,dtype='i4'			)
        lowercase_	:				Optional[Any]													=	model.decode(
            decoder_input_ids[:, -1:]     ,__UpperCamelCase     ,past_key_values=outputs_cache.past_key_values     ,decoder_attention_mask=__UpperCamelCase     ,decoder_position_ids=__UpperCamelCase     ,)

        lowercase_	:				Union[str, Any]													=	model.decode(__UpperCamelCase     ,__UpperCamelCase     ,decoder_attention_mask=__UpperCamelCase			)

        lowercase_	:				int													=	np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])			)			)
        self.parent.assertTrue(diff < 1e-3     ,msg=f'''Max diff is {diff}'''			)







@require_flax
class        UpperCamelCase		(			unittest.TestCase  ):
   lowercase							=  9_9
   def 			_UpperCAmelCase   (			self			)	->      List[Any]:


        '''simple docstring'''


        lowercase_	:				Union[str, Any]													=	np.array(
            [
                [71, 82, 18, 33, 46, 91, 2],
                [68, 34, 26, 58, 30, 82, 2],
                [5, 97, 17, 39, 94, 40, 2],
                [76, 83, 94, 25, 70, 78, 2],
                [87, 59, 41, 35, 48, 66, 2],
                [55, 13, 16, 58, 5, 2, 1],  # note padding
                [64, 27, 31, 51, 12, 75, 2],
                [52, 64, 86, 17, 83, 39, 2],
                [48, 61, 9, 24, 71, 82, 2],
                [26, 1, 60, 48, 22, 13, 2],
                [21, 5, 62, 28, 14, 76, 2],
                [45, 98, 37, 86, 59, 48, 2],
                [70, 70, 50, 9, 28, 0, 2],
            ]     ,dtype=np.intaa     ,)

        lowercase_	:				Any													=	input_ids.shape[0]
        lowercase_	:				Dict													=	BlenderbotSmallConfig(
            vocab_size=self.vocab_size     ,d_model=24     ,encoder_layers=2     ,decoder_layers=2     ,encoder_attention_heads=2     ,decoder_attention_heads=2     ,encoder_ffn_dim=32     ,decoder_ffn_dim=32     ,max_position_embeddings=48     ,eos_token_id=2     ,pad_token_id=1     ,bos_token_id=0     ,)
        return config, input_ids, batch_size
   def 			_UpperCAmelCase   (			self			)	->      str:


        '''simple docstring'''


        lowercase_							,  lowercase_							,  lowercase_	:				List[str]													=	self._get_config_and_data()
        lowercase_	:				List[str]													=	FlaxBlenderbotSmallForConditionalGeneration(__UpperCamelCase			)
        lowercase_	:				Dict													=	lm_model(input_ids=__UpperCamelCase			)
        lowercase_	:				List[Any]													=	(batch_size, input_ids.shape[1], config.vocab_size)
        self.assertEqual(outputs['logits'].shape     ,__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self			)	->      str:


        '''simple docstring'''


        lowercase_	:				Optional[int]													=	BlenderbotSmallConfig(
            vocab_size=self.vocab_size     ,d_model=14     ,encoder_layers=2     ,decoder_layers=2     ,encoder_attention_heads=2     ,decoder_attention_heads=2     ,encoder_ffn_dim=8     ,decoder_ffn_dim=8     ,max_position_embeddings=48     ,)
        lowercase_	:				Optional[int]													=	FlaxBlenderbotSmallForConditionalGeneration(__UpperCamelCase			)
        lowercase_	:				str													=	np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]]     ,dtype=np.intaa			)
        lowercase_	:				List[Any]													=	np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]]     ,dtype=np.intaa			)
        lowercase_	:				List[str]													=	lm_model(input_ids=__UpperCamelCase     ,decoder_input_ids=__UpperCamelCase			)
        lowercase_	:				Optional[Any]													=	(*summary.shape, config.vocab_size)
        self.assertEqual(outputs['logits'].shape     ,__UpperCamelCase			)







   def 			_UpperCAmelCase   (			self			)	->      int:


        '''simple docstring'''


        lowercase_	:				Union[str, Any]													=	np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]]     ,dtype=np.intaa			)
        lowercase_	:				Union[str, Any]													=	shift_tokens_right(__UpperCamelCase     ,1     ,2			)
        lowercase_	:				Optional[int]													=	np.equal(__UpperCamelCase     ,1			).astype(np.floataa			).sum()
        lowercase_	:				List[str]													=	np.equal(__UpperCamelCase     ,1			).astype(np.floataa			).sum()
        self.assertEqual(shifted.shape     ,input_ids.shape			)
        self.assertEqual(__UpperCamelCase     ,n_pad_before - 1			)
        self.assertTrue(np.equal(shifted[:, 0]     ,2			).all()			)







@require_flax
class        UpperCamelCase		(			lowercase_						,      unittest.TestCase						,      lowercase_  ):
   lowercase							=  True
   lowercase							=  (
       (
           FlaxBlenderbotSmallModel,
           FlaxBlenderbotSmallForConditionalGeneration,
       )
       if is_flax_available()
       else ()
   )
   lowercase							=  (FlaxBlenderbotSmallForConditionalGeneration,) if is_flax_available() else ()
   def 			_UpperCAmelCase   (			self			)	->      List[Any]:


        '''simple docstring'''


        lowercase_	:				str													=	FlaxBlenderbotSmallModelTester(self			)
   def 			_UpperCAmelCase   (			self			)	->      List[str]:


        '''simple docstring'''


        lowercase_							,  lowercase_	:				Tuple													=	self.model_tester.prepare_config_and_inputs()
        for model_class in self.all_model_classes:
             self.model_tester.check_use_cache_forward(__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self			)	->      List[Any]:


        '''simple docstring'''


        lowercase_							,  lowercase_	:				Optional[int]													=	self.model_tester.prepare_config_and_inputs()
        for model_class in self.all_model_classes:
             self.model_tester.check_use_cache_forward_with_attn_mask(__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self			)	->      Optional[int]:


        '''simple docstring'''


        lowercase_							,  lowercase_	:				Tuple													=	self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             with self.subTest(model_class.__name__			):
                  lowercase_	:				Dict													=	self._prepare_for_class(__UpperCamelCase     ,__UpperCamelCase			)
                  lowercase_	:				str													=	model_class(__UpperCamelCase			)

                  @jax.jit
                  def encode_jitted(__UpperCamelCase     ,__UpperCamelCase=None     ,**__UpperCamelCase			):
                       return model.encode(input_ids=__UpperCamelCase     ,attention_mask=__UpperCamelCase			)

                  with self.subTest('JIT Enabled'			):
                       lowercase_	:				Optional[int]													=	encode_jitted(**__UpperCamelCase			).to_tuple()

                  with self.subTest('JIT Disabled'			):
                       with jax.disable_jit():
                            lowercase_	:				Optional[Any]													=	encode_jitted(**__UpperCamelCase			).to_tuple()

                  self.assertEqual(len(__UpperCamelCase			)     ,len(__UpperCamelCase			)			)
                  for jitted_output, output in zip(__UpperCamelCase     ,__UpperCamelCase			):
                       self.assertEqual(jitted_output.shape     ,output.shape			)
   def 			_UpperCAmelCase   (			self			)	->      Tuple:


        '''simple docstring'''


        lowercase_							,  lowercase_	:				List[Any]													=	self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             with self.subTest(model_class.__name__			):
                  lowercase_	:				Union[str, Any]													=	model_class(__UpperCamelCase			)
                  lowercase_	:				Dict													=	model.encode(inputs_dict['input_ids']     ,inputs_dict['attention_mask']			)

                  lowercase_	:				int													=	{
                      'decoder_input_ids': inputs_dict['decoder_input_ids'],
                      'decoder_attention_mask': inputs_dict['decoder_attention_mask'],
                      'encoder_outputs': encoder_outputs,
                  }

                  @jax.jit
                  def decode_jitted(__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase			):
                       return model.decode(
                           decoder_input_ids=__UpperCamelCase     ,decoder_attention_mask=__UpperCamelCase     ,encoder_outputs=__UpperCamelCase     ,)

                  with self.subTest('JIT Enabled'			):
                       lowercase_	:				str													=	decode_jitted(**__UpperCamelCase			).to_tuple()

                  with self.subTest('JIT Disabled'			):
                       with jax.disable_jit():
                            lowercase_	:				Union[str, Any]													=	decode_jitted(**__UpperCamelCase			).to_tuple()

                  self.assertEqual(len(__UpperCamelCase			)     ,len(__UpperCamelCase			)			)
                  for jitted_output, output in zip(__UpperCamelCase     ,__UpperCamelCase			):
                       self.assertEqual(jitted_output.shape     ,output.shape			)







   @slow
   def 			_UpperCAmelCase   (			self			)	->      Any:


        '''simple docstring'''


        for model_class_name in self.all_model_classes:
             lowercase_	:				Dict													=	model_class_name.from_pretrained('facebook/blenderbot_small-90M'			)
             # FlaxBlenderbotForSequenceClassification expects eos token in input_ids
             lowercase_	:				Dict													=	np.ones((1, 1)			) * model.config.eos_token_id
             lowercase_	:				Dict													=	model(__UpperCamelCase			)
             self.assertIsNotNone(__UpperCamelCase			)


"""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        UpperCamelCase		(			lowercase_  ):
   lowercase							=  42







class        UpperCamelCase		(			lowercase_						,      lowercase_  ):
   @register_to_config
   def __init__(			self     ,__UpperCamelCase = 32     ,__UpperCamelCase = 64     ,__UpperCamelCase = 20     ,__UpperCamelCase = 768     ,__UpperCamelCase=77     ,__UpperCamelCase=4     ,__UpperCamelCase = 0.0     ,__UpperCamelCase = "silu"     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = "linear"     ,__UpperCamelCase = "prd"     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,)	->      List[str]:


        '''simple docstring'''


        super().__init__()
        lowercase_	:				Dict													=	num_attention_heads
        lowercase_	:				Dict													=	attention_head_dim
        lowercase_	:				Any													=	num_attention_heads * attention_head_dim
        lowercase_	:				Optional[Any]													=	additional_embeddings

        lowercase_	:				int													=	time_embed_dim or inner_dim
        lowercase_	:				Optional[Any]													=	embedding_proj_dim or embedding_dim
        lowercase_	:				List[str]													=	clip_embed_dim or embedding_dim

        lowercase_	:				Union[str, Any]													=	Timesteps(__UpperCamelCase     ,__UpperCamelCase     ,0			)
        lowercase_	:				Tuple													=	TimestepEmbedding(__UpperCamelCase     ,__UpperCamelCase     ,out_dim=__UpperCamelCase     ,act_fn=__UpperCamelCase			)

        lowercase_	:				Optional[Any]													=	nn.Linear(__UpperCamelCase     ,__UpperCamelCase			)

        if embedding_proj_norm_type is None:
             lowercase_	:				Dict													=	None
        elif embedding_proj_norm_type == "layer":
             lowercase_	:				str													=	nn.LayerNorm(__UpperCamelCase			)
        else:
             raise ValueError(f'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}'''			)

        lowercase_	:				Tuple													=	nn.Linear(__UpperCamelCase     ,__UpperCamelCase			)

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

        lowercase_	:				List[Any]													=	nn.Parameter(torch.zeros(1     ,num_embeddings + additional_embeddings     ,__UpperCamelCase			)			)

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

        lowercase_	:				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":
             lowercase_	:				Optional[int]													=	nn.LayerNorm(__UpperCamelCase			)
        elif norm_in_type is None:
             lowercase_	:				Dict													=	None
        else:
             raise ValueError(f'''Unsupported norm_in_type: {norm_in_type}.'''			)

        lowercase_	:				List[Any]													=	nn.LayerNorm(__UpperCamelCase			)

        lowercase_	:				Optional[int]													=	nn.Linear(__UpperCamelCase     ,__UpperCamelCase			)

        lowercase_	:				Dict													=	torch.full(
            [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings]     ,-1_0000.0			)
        causal_attention_mask.triu_(1			)
        lowercase_	:				int													=	causal_attention_mask[None, ...]
        self.register_buffer('causal_attention_mask'     ,__UpperCamelCase     ,persistent=__UpperCamelCase			)

        lowercase_	:				List[Any]													=	nn.Parameter(torch.zeros(1     ,__UpperCamelCase			)			)
        lowercase_	:				Optional[int]													=	nn.Parameter(torch.zeros(1     ,__UpperCamelCase			)			)
   @property
   # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
   def 			_UpperCAmelCase   (			self			)	->      Dict[str, AttentionProcessor]:


        '''simple docstring'''


        lowercase_	:				Tuple													=	{}

        def fn_recursive_add_processors(__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase			):
             if hasattr(__UpperCamelCase     ,'set_processor'			):
                  lowercase_	:				List[str]													=	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 			_UpperCAmelCase   (			self     ,__UpperCamelCase			)	->      Optional[Any]:


        '''simple docstring'''


        lowercase_	:				Dict													=	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     ,__UpperCamelCase     ,__UpperCamelCase			):
             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 			_UpperCAmelCase   (			self			)	->      List[str]:


        '''simple docstring'''


        self.set_attn_processor(AttnProcessor()			)
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = True     ,)	->      Any:


        '''simple docstring'''


        lowercase_	:				Any													=	hidden_states.shape[0]

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

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

        lowercase_	:				Any													=	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.
        lowercase_	:				List[Any]													=	timesteps_projected.to(dtype=self.dtype			)
        lowercase_	:				Any													=	self.time_embedding(__UpperCamelCase			)

        if self.embedding_proj_norm is not None:
             lowercase_	:				List[str]													=	self.embedding_proj_norm(__UpperCamelCase			)

        lowercase_	:				Any													=	self.embedding_proj(__UpperCamelCase			)
        if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
             lowercase_	:				Optional[int]													=	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'			)

        lowercase_	:				List[Any]													=	self.proj_in(__UpperCamelCase			)

        lowercase_	:				List[str]													=	self.positional_embedding.to(hidden_states.dtype			)

        lowercase_	:				Dict													=	[]
        lowercase_	:				Tuple													=	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:
             lowercase_	:				List[Any]													=	proj_embeddings[:, None, :]

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

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

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

        lowercase_	:				int													=	torch.cat(
            __UpperCamelCase     ,dim=1     ,)

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

        lowercase_	:				Dict													=	hidden_states + positional_embeddings

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

        if self.norm_in is not None:
             lowercase_	:				Optional[Any]													=	self.norm_in(__UpperCamelCase			)

        for block in self.transformer_blocks:
             lowercase_	:				int													=	block(__UpperCamelCase     ,attention_mask=__UpperCamelCase			)

        lowercase_	:				str													=	self.norm_out(__UpperCamelCase			)

        if self.prd_embedding is not None:
             lowercase_	:				Tuple													=	hidden_states[:, -1]
        else:
             lowercase_	:				List[Any]													=	hidden_states[:, additional_embeddings_len:]

        lowercase_	:				str													=	self.proj_to_clip_embeddings(__UpperCamelCase			)

        if not return_dict:
             return (predicted_image_embedding,)

        return PriorTransformerOutput(predicted_image_embedding=__UpperCamelCase			)







   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase			)	->      int:


        '''simple docstring'''


        lowercase_	:				Optional[Any]													=	(prior_latents * self.clip_std) + self.clip_mean
        return prior_latents

