"""simple docstring"""







import tempfile
import unittest

from transformers import TaConfig, is_torch_available
from transformers.testing_utils import (
    require_sentencepiece,
    require_tokenizers,
    require_torch,
    slow,
    torch_device,
)

from ...generation.test_utils import GenerationTesterMixin
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch

       from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel







class        UpperCamelCase		:
   def __init__(			self     ,__UpperCamelCase     ,__UpperCamelCase=99     ,__UpperCamelCase=13     ,__UpperCamelCase=7     ,__UpperCamelCase=9     ,__UpperCamelCase=True     ,__UpperCamelCase=True     ,__UpperCamelCase=False     ,__UpperCamelCase=32     ,__UpperCamelCase=5     ,__UpperCamelCase=4     ,__UpperCamelCase=37     ,__UpperCamelCase=8     ,__UpperCamelCase=0.1     ,__UpperCamelCase=0.002     ,__UpperCamelCase=1     ,__UpperCamelCase=0     ,__UpperCamelCase=0     ,__UpperCamelCase=None     ,__UpperCamelCase=None     ,)	->      Optional[int]:


        '''simple docstring'''


        lowercase_	:				int													=	parent
        lowercase_	:				Any													=	batch_size
        lowercase_	:				Optional[int]													=	encoder_seq_length
        lowercase_	:				List[str]													=	decoder_seq_length
        # For common tests
        lowercase_	:				Optional[int]													=	self.decoder_seq_length
        lowercase_	:				Tuple													=	is_training
        lowercase_	:				Dict													=	use_attention_mask
        lowercase_	:				List[Any]													=	use_labels
        lowercase_	:				Dict													=	vocab_size
        lowercase_	:				Dict													=	hidden_size
        lowercase_	:				List[Any]													=	num_hidden_layers
        lowercase_	:				List[str]													=	num_attention_heads
        lowercase_	:				Any													=	d_ff
        lowercase_	:				Tuple													=	relative_attention_num_buckets
        lowercase_	:				int													=	dropout_rate
        lowercase_	:				Union[str, Any]													=	initializer_factor
        lowercase_	:				Optional[Any]													=	eos_token_id
        lowercase_	:				str													=	pad_token_id
        lowercase_	:				List[str]													=	decoder_start_token_id
        lowercase_	:				str													=	None
        lowercase_	:				Any													=	decoder_layers
   def 			_UpperCAmelCase   (			self			)	->      Tuple:


        '''simple docstring'''


        return TaConfig.from_pretrained('google/umt5-base'			)
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase=None     ,__UpperCamelCase=None     ,__UpperCamelCase=None     ,__UpperCamelCase=None     ,__UpperCamelCase=None     ,)	->      List[str]:


        '''simple docstring'''


        if attention_mask is None:
             lowercase_	:				int													=	input_ids.ne(config.pad_token_id			)
        if decoder_attention_mask is None:
             lowercase_	:				Tuple													=	decoder_input_ids.ne(config.pad_token_id			)
        if head_mask is None:
             lowercase_	:				Optional[Any]													=	torch.ones(config.num_hidden_layers     ,config.num_attention_heads     ,device=__UpperCamelCase			)
        if decoder_head_mask is None:
             lowercase_	:				int													=	torch.ones(config.num_decoder_layers     ,config.num_attention_heads     ,device=__UpperCamelCase			)
        if cross_attn_head_mask is None:
             lowercase_	:				List[Any]													=	torch.ones(
                 config.num_decoder_layers     ,config.num_attention_heads     ,device=__UpperCamelCase			)
        return {
            "input_ids": input_ids,
            "decoder_input_ids": decoder_input_ids,
            "attention_mask": attention_mask,
            "decoder_attention_mask": decoder_attention_mask,
            "head_mask": head_mask,
            "decoder_head_mask": decoder_head_mask,
            "cross_attn_head_mask": cross_attn_head_mask,
        }
   def 			_UpperCAmelCase   (			self			)	->      List[str]:


        '''simple docstring'''


        lowercase_	:				Optional[int]													=	ids_tensor([self.batch_size, self.encoder_seq_length]     ,self.vocab_size			)
        lowercase_	:				Optional[int]													=	ids_tensor([self.batch_size, self.decoder_seq_length]     ,self.vocab_size			)

        # we need to clamp the input ids here to avoid having pad token in between
        # this is because for NllbMoe the position_ids are prepared such that
        # all pad tokens have pos id = 2 and rest are between 2..seq_length
        # and the seq_length here is seq_length - num_pad_tokens
        # but when using past, there is no way of knowing if the past input ids had
        # pad tokens in them, which results in incorrect seq_lenth and which in turn results in
        # position_ids being off by num_pad_tokens in past input
        lowercase_	:				int													=	input_ids.clamp(self.pad_token_id + 1			)
        lowercase_	:				List[Any]													=	decoder_input_ids.clamp(self.pad_token_id + 1			)

        lowercase_	:				int													=	self.get_config()
        lowercase_	:				Optional[int]													=	config.num_attention_heads
        lowercase_	:				Union[str, Any]													=	self.prepare_inputs_dict(__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase			)
        return config, input_dict
   def 			_UpperCAmelCase   (			self			)	->      Any:


        '''simple docstring'''


        lowercase_							,  lowercase_	:				Optional[int]													=	self.prepare_config_and_inputs()
        return config, inputs_dict
   def 			_UpperCAmelCase   (			self			)	->      Union[str, Any]:


        '''simple docstring'''


        return TaConfig(
            vocab_size=166     ,d_model=self.hidden_size     ,d_ff=self.d_ff     ,d_kv=self.hidden_size // self.num_attention_heads     ,num_layers=self.num_hidden_layers     ,num_decoder_layers=self.decoder_layers     ,num_heads=self.num_attention_heads     ,relative_attention_num_buckets=self.relative_attention_num_buckets     ,dropout_rate=self.dropout_rate     ,initializer_factor=self.initializer_factor     ,eos_token_id=self.eos_token_id     ,bos_token_id=self.pad_token_id     ,pad_token_id=self.pad_token_id     ,decoder_start_token_id=self.decoder_start_token_id     ,)
   def 			_UpperCAmelCase   (			self			)	->      Optional[Any]:


        '''simple docstring'''


        return TaConfig(
            vocab_size=self.vocab_size     ,d_model=self.hidden_size     ,d_ff=self.d_ff     ,d_kv=self.hidden_size // self.num_attention_heads     ,num_layers=self.num_hidden_layers     ,num_decoder_layers=self.decoder_layers     ,num_heads=self.num_attention_heads     ,relative_attention_num_buckets=self.relative_attention_num_buckets     ,dropout_rate=self.dropout_rate     ,initializer_factor=self.initializer_factor     ,eos_token_id=self.eos_token_id     ,bos_token_id=self.pad_token_id     ,pad_token_id=self.pad_token_id     ,decoder_start_token_id=self.decoder_start_token_id     ,)
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,)	->      str:


        '''simple docstring'''


        lowercase_	:				Dict													=	UMTaModel(config=__UpperCamelCase			)
        model.to(__UpperCamelCase			)
        model.eval()
        lowercase_	:				Any													=	model(
            input_ids=__UpperCamelCase     ,decoder_input_ids=__UpperCamelCase     ,attention_mask=__UpperCamelCase     ,decoder_attention_mask=__UpperCamelCase     ,)
        lowercase_	:				Tuple													=	model(input_ids=__UpperCamelCase     ,decoder_input_ids=__UpperCamelCase			)
        lowercase_	:				Optional[int]													=	result.last_hidden_state
        lowercase_	:				Tuple													=	result.past_key_values
        lowercase_	:				List[Any]													=	result.encoder_last_hidden_state

        self.parent.assertEqual(encoder_output.size()     ,(self.batch_size, self.encoder_seq_length, self.hidden_size)			)
        self.parent.assertEqual(decoder_output.size()     ,(self.batch_size, self.decoder_seq_length, self.hidden_size)			)
        # There should be `num_layers` key value embeddings stored in decoder_past
        self.parent.assertEqual(len(__UpperCamelCase			)     ,config.num_layers			)
        # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple
        self.parent.assertEqual(len(decoder_past[0]			)     ,4			)
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,)	->      Any:


        '''simple docstring'''


        lowercase_	:				Optional[int]													=	UMTaModel(config=__UpperCamelCase			).get_decoder().to(__UpperCamelCase			).eval()
        # first forward pass
        lowercase_	:				Optional[Any]													=	model(__UpperCamelCase     ,use_cache=__UpperCamelCase			)
        lowercase_	:				Union[str, Any]													=	model(__UpperCamelCase			)
        lowercase_	:				Tuple													=	model(__UpperCamelCase     ,use_cache=__UpperCamelCase			)

        self.parent.assertTrue(len(__UpperCamelCase			) == len(__UpperCamelCase			)			)
        self.parent.assertTrue(len(__UpperCamelCase			) == len(__UpperCamelCase			) + 1			)

        lowercase_							,  lowercase_	:				List[Any]													=	outputs.to_tuple()

        # create hypothetical next token and extent to next_input_ids
        lowercase_	:				Optional[int]													=	ids_tensor((self.batch_size, 1)     ,config.vocab_size			)

        # append to next input_ids and
        lowercase_	:				List[str]													=	torch.cat([input_ids, next_tokens]     ,dim=-1			)

        lowercase_	:				List[str]													=	model(__UpperCamelCase			)['last_hidden_state']
        lowercase_	:				int													=	model(__UpperCamelCase     ,past_key_values=__UpperCamelCase			)['last_hidden_state']

        # select random slice
        lowercase_	:				Optional[int]													=	ids_tensor((1,)     ,output_from_past.shape[-1]			).item()
        lowercase_	:				List[str]													=	output_from_no_past[:, -1, random_slice_idx].detach()
        lowercase_	:				Union[str, Any]													=	output_from_past[:, 0, random_slice_idx].detach()

        # test that outputs are equal for slice
        self.parent.assertTrue(torch.allclose(__UpperCamelCase     ,__UpperCamelCase     ,atol=1e-3			)			)







   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase     ,)	->      Tuple:


        '''simple docstring'''


        lowercase_	:				Dict													=	UMTaModel(config=__UpperCamelCase			).to(__UpperCamelCase			).half().eval()
        lowercase_	:				Union[str, Any]													=	model(**__UpperCamelCase			)['last_hidden_state']
        self.parent.assertFalse(torch.isnan(__UpperCamelCase			).any().item()			)







@require_torch
class        UpperCamelCase		(			lowercase_						,      lowercase_						,      lowercase_						,      unittest.TestCase  ):
   lowercase							=  (
       (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else ()
   )
   lowercase							=  (UMTaForConditionalGeneration,) if is_torch_available() else ()
   lowercase							=  (
       {
           'conversational': UMTaForConditionalGeneration,
           'feature-extraction': UMTaModel,
           'summarization': UMTaForConditionalGeneration,
           'text2text-generation': UMTaForConditionalGeneration,
           'translation': UMTaForConditionalGeneration,
           'question-answering': UMTaForQuestionAnswering,
       }
       if is_torch_available()
       else {}
   )
   lowercase							=  True
   lowercase							=  False
   lowercase							=  False
   lowercase							=  True
   lowercase							=  True
   # The small UMT5 model needs higher percentages for CPU/MP tests
   lowercase							=  [0.8, 0.9]
   def 			_UpperCAmelCase   (			self			)	->      Tuple:


        '''simple docstring'''


        lowercase_	:				Dict													=	UMTaModelTester(self			)
   @unittest.skip('Test has a segmentation fault on torch 1.8.0'			)
   def 			_UpperCAmelCase   (			self			)	->      List[Any]:


        '''simple docstring'''


        lowercase_	:				Optional[Any]													=	self.model_tester.prepare_config_and_inputs()
        lowercase_	:				int													=	UMTaModel(config_and_inputs[0]			).to(__UpperCamelCase			)
        with tempfile.TemporaryDirectory() as tmpdirname:
             torch.onnx.export(
                 __UpperCamelCase     ,(config_and_inputs[1], config_and_inputs[3], config_and_inputs[2])     ,f'''{tmpdirname}/t5_test.onnx'''     ,export_params=__UpperCamelCase     ,opset_version=9     ,input_names=['input_ids', 'decoder_input_ids']     ,)
   @unittest.skipIf(torch_device == 'cpu'     ,'Cant do half precision'			)
   def 			_UpperCAmelCase   (			self			)	->      List[Any]:


        '''simple docstring'''


        lowercase_	:				List[str]													=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model_fpaa_forward(*__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self			)	->      Tuple:


        '''simple docstring'''


        lowercase_	:				Optional[int]													=	['encoder_attentions', 'decoder_attentions', 'cross_attentions']
        lowercase_	:				Any													=	self.model_tester.prepare_config_and_inputs()
        lowercase_	:				List[Any]													=	config_and_inputs[0]
        lowercase_	:				Optional[Any]													=	UMTaForConditionalGeneration(__UpperCamelCase			).eval()
        model.to(__UpperCamelCase			)

        lowercase_	:				Dict													=	{
            'head_mask': torch.zeros(config.num_layers     ,config.num_heads     ,device=__UpperCamelCase			),
            'decoder_head_mask': torch.zeros(config.num_decoder_layers     ,config.num_heads     ,device=__UpperCamelCase			),
            'cross_attn_head_mask': torch.zeros(config.num_decoder_layers     ,config.num_heads     ,device=__UpperCamelCase			),
        }

        for attn_name, (name, mask) in zip(__UpperCamelCase     ,head_masking.items()			):
             lowercase_	:				int													=	{name: mask}
             # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified
             if name == "head_mask":
                  lowercase_	:				Tuple													=	torch.ones(
                      config.num_decoder_layers     ,config.num_heads     ,device=__UpperCamelCase			)

             lowercase_	:				List[str]													=	model.generate(
                 config_and_inputs[1]['input_ids']     ,num_beams=1     ,max_length=3     ,output_attentions=__UpperCamelCase     ,return_dict_in_generate=__UpperCamelCase     ,**__UpperCamelCase     ,)
             # We check the state of decoder_attentions and cross_attentions just from the last step
             lowercase_	:				str													=	out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1]
             self.assertEqual(sum([w.sum().item() for w in attn_weights]			)     ,0.0			)







   @unittest.skip('Does not work on the tiny model as we keep hitting edge cases.'			)
   def 			_UpperCAmelCase   (			self			)	->      Any:


        '''simple docstring'''


        pass







@require_torch
@require_sentencepiece
@require_tokenizers
class        UpperCamelCase		(			unittest.TestCase  ):
   @slow
   @unittest.skip(
       'Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged'			)
   def 			_UpperCAmelCase   (			self			)	->      List[str]:


        '''simple docstring'''


        lowercase_	:				Union[str, Any]													=	UMTaForConditionalGeneration.from_pretrained('google/umt5-small'     ,return_dict=__UpperCamelCase			).to(__UpperCamelCase			)
        lowercase_	:				Dict													=	AutoTokenizer.from_pretrained('google/umt5-small'     ,use_fast=__UpperCamelCase     ,legacy=__UpperCamelCase			)
        lowercase_	:				Any													=	[
            'Bonjour monsieur <extra_id_0> bien <extra_id_1>.',
            'No se como puedo <extra_id_0>.',
            'This is the reason why we <extra_id_0> them.',
            'The <extra_id_0> walks in <extra_id_1>, seats',
            'A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.',
        ]
        lowercase_	:				Tuple													=	tokenizer(__UpperCamelCase     ,return_tensors='pt'     ,padding=__UpperCamelCase			).input_ids
        # fmt: off
        lowercase_	:				Union[str, Any]													=	torch.tensor(
            [
                [ 3_8530, 21_0703, 25_6299, 1410, 25_6298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0],
                [   826, 321, 671, 2_5922, 25_6299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0],
                [  1460, 339, 312, 1_9014, 1_0620, 758, 25_6299, 2355,274, 1, 0, 0, 0, 0, 0, 0,0, 0],
                [   517, 25_6299, 1_4869, 281, 301, 25_6298, 275, 11_9983,1, 0, 0, 0, 0, 0, 0, 0,0, 0],
                [   320, 25_6299, 1_4869, 281, 2234, 289, 2275, 333,6_1391, 289, 25_6298, 543, 25_6297, 16_8714, 329, 25_6296,274, 1],
            ]			)
        # fmt: on
        torch.testing.assert_allclose(__UpperCamelCase     ,__UpperCamelCase			)

        lowercase_	:				Union[str, Any]													=	model.generate(input_ids.to(__UpperCamelCase			)			)
        lowercase_	:				Tuple													=	[
            '<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>',
            '<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>',
            '<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>',
            '<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>',
            '<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>',
        ]
        lowercase_	:				Dict													=	tokenizer.batch_decode(__UpperCamelCase			)
        self.assertEqual(__UpperCamelCase     ,__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

