






'''simple docstring'''




import unittest

from transformers import XLMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

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


if is_torch_available():
    import torch

    from transformers import (
        XLMForMultipleChoice,
        XLMForQuestionAnswering,
        XLMForQuestionAnsweringSimple,
        XLMForSequenceClassification,
        XLMForTokenClassification,
        XLMModel,
        XLMWithLMHeadModel,
    )
    from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST

class   _UpperCAmelCase     :




   """simple docstring"""

   def __init__(						self					:      Any , __UpperCAmelCase					:      str , __UpperCAmelCase					:      List[str]=13 , __UpperCAmelCase					:      Dict=7 , __UpperCAmelCase					:      int=True , __UpperCAmelCase					:      Optional[int]=True , __UpperCAmelCase					:      Dict=True , __UpperCAmelCase					:      Union[str, Any]=True , __UpperCAmelCase					:      List[Any]=True , __UpperCAmelCase					:      Optional[int]=False , __UpperCAmelCase					:      List[Any]=False , __UpperCAmelCase					:      Optional[int]=False , __UpperCAmelCase					:      Any=2 , __UpperCAmelCase					:      Dict=99 , __UpperCAmelCase					:      List[str]=0 , __UpperCAmelCase					:      List[Any]=32 , __UpperCAmelCase					:      Dict=5 , __UpperCAmelCase					:      Tuple=4 , __UpperCAmelCase					:      str=0.1 , __UpperCAmelCase					:      Tuple=0.1 , __UpperCAmelCase					:      int=512 , __UpperCAmelCase					:      int=2 , __UpperCAmelCase					:      str=0.02 , __UpperCAmelCase					:      Union[str, Any]=2 , __UpperCAmelCase					:      int=4 , __UpperCAmelCase					:      List[Any]="last" , __UpperCAmelCase					:      Optional[int]=True , __UpperCAmelCase					:      List[Any]=None , __UpperCAmelCase					:      Optional[int]=0 , ):





         '''simple docstring'''





         _A     	=      parent
         _A     	=      batch_size
         _A     	=      seq_length
         _A     	=      is_training
         _A     	=      use_input_lengths
         _A     	=      use_token_type_ids
         _A     	=      use_labels
         _A     	=      gelu_activation
         _A     	=      sinusoidal_embeddings
         _A     	=      causal
         _A     	=      asm
         _A     	=      n_langs
         _A     	=      vocab_size
         _A     	=      n_special
         _A     	=      hidden_size
         _A     	=      num_hidden_layers
         _A     	=      num_attention_heads
         _A     	=      hidden_dropout_prob
         _A     	=      attention_probs_dropout_prob
         _A     	=      max_position_embeddings
         _A     	=      type_sequence_label_size
         _A     	=      initializer_range
         _A     	=      num_labels
         _A     	=      num_choices
         _A     	=      summary_type
         _A     	=      use_proj
         _A     	=      scope
         _A     	=      bos_token_id

   def 		lowerCAmelCase					(						self					:      List[Any]						):





         '''simple docstring'''





         _A     	=      ids_tensor([self.batch_size, self.seq_length] , self.vocab_size						)
         _A     	=      random_attention_mask([self.batch_size, self.seq_length]						)

         _A     	=      None
         if self.use_input_lengths:
               _A     	=      (
                   ids_tensor([self.batch_size] , vocab_size=2						) + self.seq_length - 2
               )  # small variation of seq_length

         _A     	=      None
         if self.use_token_type_ids:
               _A     	=      ids_tensor([self.batch_size, self.seq_length] , self.n_langs						)

         _A     	=      None
         _A     	=      None
         _A     	=      None
         if self.use_labels:
               _A     	=      ids_tensor([self.batch_size] , self.type_sequence_label_size						)
               _A     	=      ids_tensor([self.batch_size, self.seq_length] , self.num_labels						)
               _A     	=      ids_tensor([self.batch_size] , 2						).float()
               _A     	=      ids_tensor([self.batch_size] , self.num_choices						)

         _A     	=      self.get_config()

         return (
             config,
             input_ids,
             token_type_ids,
             input_lengths,
             sequence_labels,
             token_labels,
             is_impossible_labels,
             choice_labels,
             input_mask,
         )

   def 		lowerCAmelCase					(						self					:      Optional[Any]						):





         '''simple docstring'''





         return XLMConfig(
             vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , )

   def 		lowerCAmelCase					(						self					:      Union[str, Any] , __UpperCAmelCase					:      List[str] , __UpperCAmelCase					:      List[Any] , __UpperCAmelCase					:      int , __UpperCAmelCase					:      str , __UpperCAmelCase					:      Optional[Any] , __UpperCAmelCase					:      Optional[int] , __UpperCAmelCase					:      int , __UpperCAmelCase					:      str , __UpperCAmelCase					:      int , ):





         '''simple docstring'''





         _A     	=      XLMModel(config=__SCREAMING_SNAKE_CASE						)
         model.to(__SCREAMING_SNAKE_CASE						)
         model.eval()
         _A     	=      model(__SCREAMING_SNAKE_CASE , lengths=__SCREAMING_SNAKE_CASE , langs=__SCREAMING_SNAKE_CASE						)
         _A     	=      model(__SCREAMING_SNAKE_CASE , langs=__SCREAMING_SNAKE_CASE						)
         _A     	=      model(__SCREAMING_SNAKE_CASE						)
         self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)						)

   def 		lowerCAmelCase					(						self					:      str , __UpperCAmelCase					:      Any , __UpperCAmelCase					:      Tuple , __UpperCAmelCase					:      str , __UpperCAmelCase					:      Optional[Any] , __UpperCAmelCase					:      str , __UpperCAmelCase					:      List[Any] , __UpperCAmelCase					:      Union[str, Any] , __UpperCAmelCase					:      str , __UpperCAmelCase					:      str , ):





         '''simple docstring'''





         _A     	=      XLMWithLMHeadModel(__SCREAMING_SNAKE_CASE						)
         model.to(__SCREAMING_SNAKE_CASE						)
         model.eval()

         _A     	=      model(__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE						)
         self.parent.assertEqual(result.loss.shape , ()						)
         self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)						)

   def 		lowerCAmelCase					(						self					:      Union[str, Any] , __UpperCAmelCase					:      Any , __UpperCAmelCase					:      Dict , __UpperCAmelCase					:      Union[str, Any] , __UpperCAmelCase					:      List[str] , __UpperCAmelCase					:      List[Any] , __UpperCAmelCase					:      List[str] , __UpperCAmelCase					:      Optional[Any] , __UpperCAmelCase					:      Dict , __UpperCAmelCase					:      Optional[int] , ):





         '''simple docstring'''





         _A     	=      XLMForQuestionAnsweringSimple(__SCREAMING_SNAKE_CASE						)
         model.to(__SCREAMING_SNAKE_CASE						)
         model.eval()

         _A     	=      model(__SCREAMING_SNAKE_CASE						)

         _A     	=      model(__SCREAMING_SNAKE_CASE , start_positions=__SCREAMING_SNAKE_CASE , end_positions=__SCREAMING_SNAKE_CASE						)
         _A     	=      outputs
         self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)						)
         self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)						)

   def 		lowerCAmelCase					(						self					:      Optional[Any] , __UpperCAmelCase					:      List[str] , __UpperCAmelCase					:      str , __UpperCAmelCase					:      Dict , __UpperCAmelCase					:      List[str] , __UpperCAmelCase					:      str , __UpperCAmelCase					:      int , __UpperCAmelCase					:      List[str] , __UpperCAmelCase					:      Optional[int] , __UpperCAmelCase					:      Optional[Any] , ):





         '''simple docstring'''





         _A     	=      XLMForQuestionAnswering(__SCREAMING_SNAKE_CASE						)
         model.to(__SCREAMING_SNAKE_CASE						)
         model.eval()

         _A     	=      model(__SCREAMING_SNAKE_CASE						)

         _A     	=      model(
             __SCREAMING_SNAKE_CASE , start_positions=__SCREAMING_SNAKE_CASE , end_positions=__SCREAMING_SNAKE_CASE , cls_index=__SCREAMING_SNAKE_CASE , is_impossible=__SCREAMING_SNAKE_CASE , p_mask=__SCREAMING_SNAKE_CASE , )

         _A     	=      model(
             __SCREAMING_SNAKE_CASE , start_positions=__SCREAMING_SNAKE_CASE , end_positions=__SCREAMING_SNAKE_CASE , cls_index=__SCREAMING_SNAKE_CASE , is_impossible=__SCREAMING_SNAKE_CASE , )

         ((_A      )	,            )     	=      result_with_labels.to_tuple()

         _A     	=      model(__SCREAMING_SNAKE_CASE , start_positions=__SCREAMING_SNAKE_CASE , end_positions=__SCREAMING_SNAKE_CASE						)

         ((_A      )	,            )     	=      result_with_labels.to_tuple()

         self.parent.assertEqual(result_with_labels.loss.shape , ()						)
         self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top)						)
         self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top)						)
         self.parent.assertEqual(
             result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top)						)
         self.parent.assertEqual(
             result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top)						)
         self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,)						)

   def 		lowerCAmelCase					(						self					:      int , __UpperCAmelCase					:      Dict , __UpperCAmelCase					:      str , __UpperCAmelCase					:      List[str] , __UpperCAmelCase					:      str , __UpperCAmelCase					:      Optional[Any] , __UpperCAmelCase					:      Optional[Any] , __UpperCAmelCase					:      Optional[Any] , __UpperCAmelCase					:      Dict , __UpperCAmelCase					:      Any , ):





         '''simple docstring'''





         _A     	=      XLMForSequenceClassification(__SCREAMING_SNAKE_CASE						)
         model.to(__SCREAMING_SNAKE_CASE						)
         model.eval()

         _A     	=      model(__SCREAMING_SNAKE_CASE						)
         _A     	=      model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE						)
         self.parent.assertEqual(result.loss.shape , ()						)
         self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)						)

   def 		lowerCAmelCase					(						self					:      int , __UpperCAmelCase					:      List[str] , __UpperCAmelCase					:      List[str] , __UpperCAmelCase					:      str , __UpperCAmelCase					:      Any , __UpperCAmelCase					:      str , __UpperCAmelCase					:      Dict , __UpperCAmelCase					:      Dict , __UpperCAmelCase					:      Tuple , __UpperCAmelCase					:      str , ):





         '''simple docstring'''





         _A     	=      self.num_labels
         _A     	=      XLMForTokenClassification(__SCREAMING_SNAKE_CASE						)
         model.to(__SCREAMING_SNAKE_CASE						)
         model.eval()

         _A     	=      model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE						)
         self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)						)

   def 		lowerCAmelCase					(						self					:      str , __UpperCAmelCase					:      Union[str, Any] , __UpperCAmelCase					:      List[Any] , __UpperCAmelCase					:      Union[str, Any] , __UpperCAmelCase					:      Dict , __UpperCAmelCase					:      Union[str, Any] , __UpperCAmelCase					:      Any , __UpperCAmelCase					:      List[str] , __UpperCAmelCase					:      Optional[int] , __UpperCAmelCase					:      List[Any] , ):





         '''simple docstring'''





         _A     	=      self.num_choices
         _A     	=      XLMForMultipleChoice(config=__SCREAMING_SNAKE_CASE						)
         model.to(__SCREAMING_SNAKE_CASE						)
         model.eval()
         _A     	=      input_ids.unsqueeze(1						).expand(-1 , self.num_choices , -1						).contiguous()
         _A     	=      token_type_ids.unsqueeze(1						).expand(-1 , self.num_choices , -1						).contiguous()
         _A     	=      input_mask.unsqueeze(1						).expand(-1 , self.num_choices , -1						).contiguous()
         _A     	=      model(
             __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , )
         self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)						)

   def 		lowerCAmelCase					(						self					:      Optional[Any]						):





         '''simple docstring'''





         _A     	=      self.prepare_config_and_inputs()
         (
             (
             _A      
         )	,      (
             _A      
         )	,      (
             _A      
         )	,      (
             _A      
         )	,      (
             _A      
         )	,      (
             _A      
         )	,      (
             _A      
         )	,      (
             _A      
         )	,      (
             _A      
         )	,            
         )     	=      config_and_inputs
         _A     	=      {"input_ids": input_ids, "token_type_ids": token_type_ids, "lengths": input_lengths}
         return config, inputs_dict





@require_torch
class   _UpperCAmelCase     (	__snake_case				,       __snake_case				,       __snake_case				,       unittest.TestCase		):




   """simple docstring"""

   snake_case       							=		(
       (
           XLMModel,
           XLMWithLMHeadModel,
           XLMForQuestionAnswering,
           XLMForSequenceClassification,
           XLMForQuestionAnsweringSimple,
           XLMForTokenClassification,
           XLMForMultipleChoice,
       )
       if is_torch_available()
       else ()
   )
   snake_case       							=		(
       (XLMWithLMHeadModel,) if is_torch_available() else ()
   )  # TODO (PVP): Check other models whether language generation is also applicable
   snake_case       							=		(
       {
           """feature-extraction""": XLMModel,
           """fill-mask""": XLMWithLMHeadModel,
           """question-answering""": XLMForQuestionAnsweringSimple,
           """text-classification""": XLMForSequenceClassification,
           """text-generation""": XLMWithLMHeadModel,
           """token-classification""": XLMForTokenClassification,
           """zero-shot""": XLMForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )

   def 		lowerCAmelCase					(						self					:      Tuple , __UpperCAmelCase					:      str , __UpperCAmelCase					:      List[Any] , __UpperCAmelCase					:      Tuple , __UpperCAmelCase					:      Tuple , __UpperCAmelCase					:      Tuple						):





         '''simple docstring'''





         if (
             pipeline_test_casse_name == "QAPipelineTests"
             and tokenizer_name is not None
             and not tokenizer_name.endswith("Fast"						)
         ):
               # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
               # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
               # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
               return True

         return False

   def 		lowerCAmelCase					(						self					:      List[Any] , __UpperCAmelCase					:      Union[str, Any] , __UpperCAmelCase					:      int , __UpperCAmelCase					:      Union[str, Any]=False						):





         '''simple docstring'''





         _A     	=      super()._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , return_labels=__SCREAMING_SNAKE_CASE						)

         if return_labels:
               if model_class.__name__ == "XLMForQuestionAnswering":
                     _A     	=      torch.zeros(
                         self.model_tester.batch_size , dtype=torch.long , device=__SCREAMING_SNAKE_CASE						)
                     _A     	=      torch.zeros(
                         self.model_tester.batch_size , dtype=torch.long , device=__SCREAMING_SNAKE_CASE						)

         return inputs_dict

   def 		lowerCAmelCase					(						self					:      Tuple						):





         '''simple docstring'''





         _A     	=      XLMModelTester(self						)
         _A     	=      ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , emb_dim=37						)

   def 		lowerCAmelCase					(						self					:      List[str]						):





         '''simple docstring'''





         self.config_tester.run_common_tests()

   def 		lowerCAmelCase					(						self					:      List[str]						):





         '''simple docstring'''





         _A     	=      self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_xlm_model(*__SCREAMING_SNAKE_CASE						)

   def 		lowerCAmelCase					(						self					:      Optional[int]						):





         '''simple docstring'''





         _A     	=      self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_xlm_lm_head(*__SCREAMING_SNAKE_CASE						)

   def 		lowerCAmelCase					(						self					:      Union[str, Any]						):





         '''simple docstring'''





         _A     	=      self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_xlm_simple_qa(*__SCREAMING_SNAKE_CASE						)

   def 		lowerCAmelCase					(						self					:      List[str]						):





         '''simple docstring'''





         _A     	=      self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_xlm_qa(*__SCREAMING_SNAKE_CASE						)

   def 		lowerCAmelCase					(						self					:      Union[str, Any]						):





         '''simple docstring'''





         _A     	=      self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_xlm_sequence_classif(*__SCREAMING_SNAKE_CASE						)

   def 		lowerCAmelCase					(						self					:      Union[str, Any]						):





         '''simple docstring'''





         _A     	=      self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_xlm_token_classif(*__SCREAMING_SNAKE_CASE						)

   def 		lowerCAmelCase					(						self					:      str						):





         '''simple docstring'''





         _A     	=      self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_xlm_for_multiple_choice(*__SCREAMING_SNAKE_CASE						)

   def 		lowerCAmelCase					(						self					:      Optional[int] , __UpperCAmelCase					:      List[Any] , __UpperCAmelCase					:      Union[str, Any] , __UpperCAmelCase					:      Union[str, Any] , __UpperCAmelCase					:      List[str] , __UpperCAmelCase					:      Tuple , __UpperCAmelCase					:      Optional[Any]=False , __UpperCAmelCase					:      List[str]=1						):





         '''simple docstring'''





         self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE						)
         self.assertListEqual(
             [isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE						) for iter_attentions in attentions] , [True] * len(__SCREAMING_SNAKE_CASE						)						)
         self.assertEqual(len(__SCREAMING_SNAKE_CASE						) , (max_length - min_length) * num_beam_groups						)

         for idx, iter_attentions in enumerate(__SCREAMING_SNAKE_CASE						):
               # adds PAD dummy token
               _A     	=      min_length + idx + 1
               _A     	=      min_length + idx + 1

               _A     	=      (
                   batch_size * num_beam_groups,
                   config.num_attention_heads,
                   tgt_len,
                   src_len,
               )
               # check attn size
               self.assertListEqual(
                   [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(__SCREAMING_SNAKE_CASE						)						)

   def 		lowerCAmelCase					(						self					:      str , __UpperCAmelCase					:      str , __UpperCAmelCase					:      List[Any] , __UpperCAmelCase					:      Dict , __UpperCAmelCase					:      List[str] , __UpperCAmelCase					:      int , __UpperCAmelCase					:      List[str]=False , __UpperCAmelCase					:      Any=1						):





         '''simple docstring'''





         self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE						)
         self.assertListEqual(
             [isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE						) for iter_hidden_states in hidden_states] , [True] * len(__SCREAMING_SNAKE_CASE						) , )
         self.assertEqual(len(__SCREAMING_SNAKE_CASE						) , (max_length - min_length) * num_beam_groups						)

         for idx, iter_hidden_states in enumerate(__SCREAMING_SNAKE_CASE						):
               # adds PAD dummy token
               _A     	=      min_length + idx + 1
               _A     	=      (batch_size * num_beam_groups, seq_len, config.hidden_size)
               # check hidden size
               self.assertListEqual(
                   [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(__SCREAMING_SNAKE_CASE						) , )
         pass

   @slow
   def 		lowerCAmelCase					(						self					:      Dict						):





         '''simple docstring'''





         for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _A     	=      XLMModel.from_pretrained(__SCREAMING_SNAKE_CASE						)
               self.assertIsNotNone(__SCREAMING_SNAKE_CASE						)





@require_torch
class   _UpperCAmelCase     (	unittest.TestCase		):




   """simple docstring"""

   @slow
   def 		lowerCAmelCase					(						self					:      Any						):





         '''simple docstring'''





         _A     	=      XLMWithLMHeadModel.from_pretrained("xlm-mlm-en-2048"						)
         model.to(__SCREAMING_SNAKE_CASE						)
         _A     	=      torch.tensor([[14, 447]] , dtype=torch.long , device=__SCREAMING_SNAKE_CASE						)  # the president
         _A     	=      [
             14,
             447,
             14,
             447,
             14,
             447,
             14,
             447,
             14,
             447,
             14,
             447,
             14,
             447,
             14,
             447,
             14,
             447,
             14,
             447,
         ]  # the president the president the president the president the president the president the president the president the president the president
         # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference
         _A     	=      model.generate(__SCREAMING_SNAKE_CASE , do_sample=__SCREAMING_SNAKE_CASE						)
         self.assertListEqual(output_ids[0].cpu().numpy().tolist() , __SCREAMING_SNAKE_CASE						)













"""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




