






'''simple docstring'''




import argparse
import glob
import logging
import os
import sys
import time
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Tuple

import numpy as np
import pytorch_lightning as pl
import torch
from callbacks import SeqaSeqLoggingCallback, get_checkpoint_callback, get_early_stopping_callback
from torch import nn
from torch.utils.data import DataLoader

from transformers import MBartTokenizer, TaForConditionalGeneration
from transformers.models.bart.modeling_bart import shift_tokens_right
from utils import (
    ROUGE_KEYS,
    LegacySeqaSeqDataset,
    SeqaSeqDataset,
    assert_all_frozen,
    calculate_bleu,
    calculate_rouge,
    check_output_dir,
    flatten_list,
    freeze_embeds,
    freeze_params,
    get_git_info,
    label_smoothed_nll_loss,
    lmap,
    pickle_save,
    save_git_info,
    save_json,
    use_task_specific_params,
)


# need the parent dir module
sys.path.insert(2, str(Path(__file__).resolve().parents[1]))
from lightning_base import BaseTransformer, add_generic_args, generic_train  # noqa


lowerCamelCase_				   =   logging.getLogger(__name__)

class   _UpperCAmelCase     (	__snake_case		):




   """simple docstring"""

   snake_case       							=		"""summarization"""
   snake_case       							=		["""loss"""]
   snake_case       							=		ROUGE_KEYS
   snake_case       							=		"""rouge2"""

   def __init__(						self					:      Optional[int] , __UpperCAmelCase					:      List[str] , **__UpperCAmelCase					:      List[str]						):





         '''simple docstring'''





         if hparams.sortish_sampler and hparams.gpus > 1:
               _A     	=      False
         elif hparams.max_tokens_per_batch is not None:
               if hparams.gpus > 1:
                     raise NotImplementedError("Dynamic Batch size does not work for multi-gpu training"						)
               if hparams.sortish_sampler:
                     raise ValueError("--sortish_sampler and --max_tokens_per_batch may not be used simultaneously"						)

         super().__init__(__SCREAMING_SNAKE_CASE , num_labels=__SCREAMING_SNAKE_CASE , mode=self.mode , **__SCREAMING_SNAKE_CASE						)
         use_task_specific_params(self.model , "summarization"						)
         save_git_info(self.hparams.output_dir						)
         _A     	=      Path(self.output_dir						) / "metrics.json"
         _A     	=      Path(self.output_dir						) / "hparams.pkl"
         pickle_save(self.hparams , self.hparams_save_path						)
         _A     	=      0
         _A     	=      defaultdict(__SCREAMING_SNAKE_CASE						)
         _A     	=      self.config.model_type
         _A     	=      self.config.tgt_vocab_size if self.model_type == "fsmt" else self.config.vocab_size

         _A     	=      {
             "data_dir": self.hparams.data_dir,
             "max_source_length": self.hparams.max_source_length,
             "prefix": self.model.config.prefix or "",
         }
         _A     	=      {
             "train": self.hparams.n_train,
             "val": self.hparams.n_val,
             "test": self.hparams.n_test,
         }
         _A     	=      {k: v if v >= 0 else None for k, v in n_observations_per_split.items()}

         _A     	=      {
             "train": self.hparams.max_target_length,
             "val": self.hparams.val_max_target_length,
             "test": self.hparams.test_max_target_length,
         }
         assert self.target_lens["train"] <= self.target_lens["val"], f'''target_lens: {self.target_lens}'''
         assert self.target_lens["train"] <= self.target_lens["test"], f'''target_lens: {self.target_lens}'''
         if self.hparams.freeze_embeds:
               freeze_embeds(self.model						)
         if self.hparams.freeze_encoder:
               freeze_params(self.model.get_encoder()						)
               assert_all_frozen(self.model.get_encoder()						)

         _A     	=      get_git_info()["repo_sha"]
         _A     	=      hparams.num_workers
         _A     	=      None  # default to config
         if self.model.config.decoder_start_token_id is None and isinstance(self.tokenizer , __SCREAMING_SNAKE_CASE						):
               _A     	=      self.tokenizer.lang_code_to_id[hparams.tgt_lang]
               _A     	=      self.decoder_start_token_id
         _A     	=      (
             SeqaSeqDataset if hasattr(self.tokenizer , "prepare_seq2seq_batch"						) else LegacySeqaSeqDataset
         )
         _A     	=      False
         _A     	=      self.model.config.num_beams if self.hparams.eval_beams is None else self.hparams.eval_beams
         if self.hparams.eval_max_gen_length is not None:
               _A     	=      self.hparams.eval_max_gen_length
         else:
               _A     	=      self.model.config.max_length
         _A     	=      self.default_val_metric if self.hparams.val_metric is None else self.hparams.val_metric

   def 		lowerCAmelCase					(						self					:      Dict , __UpperCAmelCase					:      Dict[str, torch.Tensor]						):





         '''simple docstring'''





         _A     	=      {
             k: self.tokenizer.batch_decode(v.tolist()						) if "mask" not in k else v.shape for k, v in batch.items()
         }
         save_json(__SCREAMING_SNAKE_CASE , Path(self.output_dir						) / "text_batch.json"						)
         save_json({k: v.tolist() for k, v in batch.items()} , Path(self.output_dir						) / "tok_batch.json"						)

         _A     	=      True
         return readable_batch

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





         '''simple docstring'''





         return self.model(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE						)

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





         '''simple docstring'''





         _A     	=      self.tokenizer.batch_decode(
             __SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=__SCREAMING_SNAKE_CASE						)
         return lmap(str.strip , __SCREAMING_SNAKE_CASE						)

   def 		lowerCAmelCase					(						self					:      Any , __UpperCAmelCase					:      dict						):





         '''simple docstring'''





         _A     	=      self.tokenizer.pad_token_id
         _A	,      _A     	=      batch["input_ids"], batch["attention_mask"]
         _A     	=      batch["labels"]
         if isinstance(self.model , __SCREAMING_SNAKE_CASE						):
               _A     	=      self.model._shift_right(__SCREAMING_SNAKE_CASE						)
         else:
               _A     	=      shift_tokens_right(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE						)
         if not self.already_saved_batch:  # This would be slightly better if it only happened on rank zero
               _A     	=      decoder_input_ids
               self.save_readable_batch(__SCREAMING_SNAKE_CASE						)

         _A     	=      self(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , decoder_input_ids=__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE						)
         _A     	=      outputs["logits"]
         if self.hparams.label_smoothing == 0:
               # Same behavior as modeling_bart.py, besides ignoring pad_token_id
               _A     	=      nn.CrossEntropyLoss(ignore_index=__SCREAMING_SNAKE_CASE						)

               assert lm_logits.shape[-1] == self.vocab_size
               _A     	=      ce_loss_fct(lm_logits.view(-1 , lm_logits.shape[-1]						) , tgt_ids.view(-1						)						)
         else:
               _A     	=      nn.functional.log_softmax(__SCREAMING_SNAKE_CASE , dim=-1						)
               _A	,      _A     	=      label_smoothed_nll_loss(
                   __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , self.hparams.label_smoothing , ignore_index=__SCREAMING_SNAKE_CASE						)
         return (loss,)

   @property
   def 		lowerCAmelCase					(						self					:      Optional[Any]						):





         '''simple docstring'''





         return self.tokenizer.pad_token_id

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





         '''simple docstring'''





         _A     	=      self._step(__SCREAMING_SNAKE_CASE						)

         _A     	=      dict(zip(self.loss_names , __SCREAMING_SNAKE_CASE						)						)
         # tokens per batch
         _A     	=      batch["input_ids"].ne(self.pad						).sum() + batch["labels"].ne(self.pad						).sum()
         _A     	=      batch["input_ids"].shape[0]
         _A     	=      batch["input_ids"].eq(self.pad						).sum()
         _A     	=      batch["input_ids"].eq(self.pad						).float().mean()
         # TODO(SS): make a wandb summary metric for this
         return {"loss": loss_tensors[0], "log": logs}

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





         '''simple docstring'''





         return self._generative_step(__SCREAMING_SNAKE_CASE						)

   def 		lowerCAmelCase					(						self					:      str , __UpperCAmelCase					:      Union[str, Any] , __UpperCAmelCase					:      Optional[Any]="val"						):





         '''simple docstring'''





         self.step_count += 1
         _A     	=      {k: torch.stack([x[k] for x in outputs]						).mean() for k in self.loss_names}
         _A     	=      losses["loss"]
         _A     	=      {
             k: np.array([x[k] for x in outputs]						).mean() for k in self.metric_names + ["gen_time", "gen_len"]
         }
         _A     	=      (
             generative_metrics[self.val_metric] if self.val_metric in generative_metrics else losses[self.val_metric]
         )
         _A     	=      torch.tensor(__SCREAMING_SNAKE_CASE						).type_as(__SCREAMING_SNAKE_CASE						)
         generative_metrics.update({k: v.item() for k, v in losses.items()}						)
         losses.update(__SCREAMING_SNAKE_CASE						)
         _A     	=      {f'''{prefix}_avg_{k}''': x for k, x in losses.items()}
         _A     	=      self.step_count
         self.metrics[prefix].append(__SCREAMING_SNAKE_CASE						)  # callback writes this to self.metrics_save_path
         _A     	=      flatten_list([x["preds"] for x in outputs]						)
         return {
             "log": all_metrics,
             "preds": preds,
             f'''{prefix}_loss''': loss,
             f'''{prefix}_{self.val_metric}''': metric_tensor,
         }

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





         '''simple docstring'''





         return calculate_rouge(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE						)

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





         '''simple docstring'''





         _A     	=      time.time()

         # parser.add_argument('--eval_max_gen_length', type=int, default=None, help='never generate more than n tokens')
         _A     	=      self.model.generate(
             batch["input_ids"] , attention_mask=batch["attention_mask"] , use_cache=__SCREAMING_SNAKE_CASE , decoder_start_token_id=self.decoder_start_token_id , num_beams=self.eval_beams , max_length=self.eval_max_length , )
         _A     	=      (time.time() - ta) / batch["input_ids"].shape[0]
         _A     	=      self.ids_to_clean_text(__SCREAMING_SNAKE_CASE						)
         _A     	=      self.ids_to_clean_text(batch["labels"]						)
         _A     	=      self._step(__SCREAMING_SNAKE_CASE						)
         _A     	=      dict(zip(self.loss_names , __SCREAMING_SNAKE_CASE						)						)
         _A     	=      self.calc_generative_metrics(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE						)
         _A     	=      np.mean(lmap(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE						)						)
         base_metrics.update(gen_time=__SCREAMING_SNAKE_CASE , gen_len=__SCREAMING_SNAKE_CASE , preds=__SCREAMING_SNAKE_CASE , target=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE						)
         return base_metrics

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





         '''simple docstring'''





         return self._generative_step(__SCREAMING_SNAKE_CASE						)

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





         '''simple docstring'''





         return self.validation_epoch_end(__SCREAMING_SNAKE_CASE , prefix="test"						)

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





         '''simple docstring'''





         _A     	=      self.n_obs[type_path]
         _A     	=      self.target_lens[type_path]
         _A     	=      self.dataset_class(
             self.tokenizer , type_path=__SCREAMING_SNAKE_CASE , n_obs=__SCREAMING_SNAKE_CASE , max_target_length=__SCREAMING_SNAKE_CASE , **self.dataset_kwargs , )
         return dataset

   def 		lowerCAmelCase					(						self					:      Tuple , __UpperCAmelCase					:      str , __UpperCAmelCase					:      int , __UpperCAmelCase					:      bool = False						):





         '''simple docstring'''





         _A     	=      self.get_dataset(__SCREAMING_SNAKE_CASE						)

         if self.hparams.sortish_sampler and type_path != "test" and type_path != "val":
               _A     	=      dataset.make_sortish_sampler(__SCREAMING_SNAKE_CASE , distributed=self.hparams.gpus > 1						)
               return DataLoader(
                   __SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE , collate_fn=dataset.collate_fn , shuffle=__SCREAMING_SNAKE_CASE , num_workers=self.num_workers , sampler=__SCREAMING_SNAKE_CASE , )

         elif self.hparams.max_tokens_per_batch is not None and type_path != "test" and type_path != "val":
               _A     	=      dataset.make_dynamic_sampler(
                   self.hparams.max_tokens_per_batch , distributed=self.hparams.gpus > 1						)
               return DataLoader(
                   __SCREAMING_SNAKE_CASE , batch_sampler=__SCREAMING_SNAKE_CASE , collate_fn=dataset.collate_fn , num_workers=self.num_workers , )
         else:
               return DataLoader(
                   __SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE , collate_fn=dataset.collate_fn , shuffle=__SCREAMING_SNAKE_CASE , num_workers=self.num_workers , sampler=__SCREAMING_SNAKE_CASE , )

   def 		lowerCAmelCase					(						self					:      Dict						):





         '''simple docstring'''





         _A     	=      self.get_dataloader("train" , batch_size=self.hparams.train_batch_size , shuffle=__SCREAMING_SNAKE_CASE						)
         return dataloader

   def 		lowerCAmelCase					(						self					:      int						):





         '''simple docstring'''





         return self.get_dataloader("val" , batch_size=self.hparams.eval_batch_size						)

   def 		lowerCAmelCase					(						self					:      int						):





         '''simple docstring'''





         return self.get_dataloader("test" , batch_size=self.hparams.eval_batch_size						)

   @staticmethod
   def 		lowerCAmelCase					(						__UpperCAmelCase					:      List[Any] , __UpperCAmelCase					:      Optional[int]						):





         '''simple docstring'''





         BaseTransformer.add_model_specific_args(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE						)
         add_generic_args(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE						)
         parser.add_argument(
             "--max_source_length" , default=1024 , type=__SCREAMING_SNAKE_CASE , help=(
                 "The maximum total input sequence length after tokenization. Sequences longer "
                 "than this will be truncated, sequences shorter will be padded."
             ) , )
         parser.add_argument(
             "--max_target_length" , default=56 , type=__SCREAMING_SNAKE_CASE , help=(
                 "The maximum total input sequence length after tokenization. Sequences longer "
                 "than this will be truncated, sequences shorter will be padded."
             ) , )
         parser.add_argument(
             "--val_max_target_length" , default=142 , type=__SCREAMING_SNAKE_CASE , help=(
                 "The maximum total input sequence length after tokenization. Sequences longer "
                 "than this will be truncated, sequences shorter will be padded."
             ) , )
         parser.add_argument(
             "--test_max_target_length" , default=142 , type=__SCREAMING_SNAKE_CASE , help=(
                 "The maximum total input sequence length after tokenization. Sequences longer "
                 "than this will be truncated, sequences shorter will be padded."
             ) , )
         parser.add_argument("--freeze_encoder" , action="store_true"						)
         parser.add_argument("--freeze_embeds" , action="store_true"						)
         parser.add_argument("--sortish_sampler" , action="store_true" , default=__SCREAMING_SNAKE_CASE						)
         parser.add_argument("--overwrite_output_dir" , action="store_true" , default=__SCREAMING_SNAKE_CASE						)
         parser.add_argument("--max_tokens_per_batch" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE						)
         parser.add_argument("--logger_name" , type=__SCREAMING_SNAKE_CASE , choices=["default", "wandb", "wandb_shared"] , default="default"						)
         parser.add_argument("--n_train" , type=__SCREAMING_SNAKE_CASE , default=-1 , required=__SCREAMING_SNAKE_CASE , help="# examples. -1 means use all."						)
         parser.add_argument("--n_val" , type=__SCREAMING_SNAKE_CASE , default=500 , required=__SCREAMING_SNAKE_CASE , help="# examples. -1 means use all."						)
         parser.add_argument("--n_test" , type=__SCREAMING_SNAKE_CASE , default=-1 , required=__SCREAMING_SNAKE_CASE , help="# examples. -1 means use all."						)
         parser.add_argument(
             "--task" , type=__SCREAMING_SNAKE_CASE , default="summarization" , required=__SCREAMING_SNAKE_CASE , help="# examples. -1 means use all."						)
         parser.add_argument("--label_smoothing" , type=__SCREAMING_SNAKE_CASE , default=0.0 , required=__SCREAMING_SNAKE_CASE						)
         parser.add_argument("--src_lang" , type=__SCREAMING_SNAKE_CASE , default="" , required=__SCREAMING_SNAKE_CASE						)
         parser.add_argument("--tgt_lang" , type=__SCREAMING_SNAKE_CASE , default="" , required=__SCREAMING_SNAKE_CASE						)
         parser.add_argument("--eval_beams" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE						)
         parser.add_argument(
             "--val_metric" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , choices=["bleu", "rouge2", "loss", None]						)
         parser.add_argument("--eval_max_gen_length" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help="never generate more than n tokens"						)
         parser.add_argument("--save_top_k" , type=__SCREAMING_SNAKE_CASE , default=1 , required=__SCREAMING_SNAKE_CASE , help="How many checkpoints to save"						)
         parser.add_argument(
             "--early_stopping_patience" , type=__SCREAMING_SNAKE_CASE , default=-1 , required=__SCREAMING_SNAKE_CASE , help=(
                 "-1 means never early stop. early_stopping_patience is measured in validation checks, not epochs. So"
                 " val_check_interval will effect it."
             ) , )
         return parser





class   _UpperCAmelCase     (	__snake_case		):




   """simple docstring"""

   snake_case       							=		"""translation"""
   snake_case       							=		["""loss"""]
   snake_case       							=		["""bleu"""]
   snake_case       							=		"""bleu"""

   def __init__(						self					:      str , __UpperCAmelCase					:      Dict , **__UpperCAmelCase					:      Tuple						):





         '''simple docstring'''





         super().__init__(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE						)
         _A     	=      hparams.src_lang
         _A     	=      hparams.tgt_lang

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





         '''simple docstring'''





         return calculate_bleu(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE						)





def    __lowercase		(     __lowercase  ,    __lowercase=None			)			->		SummarizationModule:

      '''simple docstring'''


      Path(args.output_dir			).mkdir(exist_ok=_lowerCamelCase			)
      check_output_dir(_lowerCamelCase  ,    expected_items=3			)

      if model is None:
            if "summarization" in args.task:
                  _A     	=      SummarizationModule(_lowerCamelCase			)
            else:
                  _A     	=      TranslationModule(_lowerCamelCase			)
      _A     	=      Path(args.data_dir			).name
      if (
          args.logger_name == "default"
          or args.fast_dev_run
          or str(args.output_dir			).startswith("/tmp"			)
          or str(args.output_dir			).startswith("/var"			)
      ):
            _A     	=      True  # don't pollute wandb logs unnecessarily
      elif args.logger_name == "wandb":
            from pytorch_lightning.loggers import WandbLogger

            _A     	=      os.environ.get("WANDB_PROJECT"  ,    _lowerCamelCase			)
            _A     	=      WandbLogger(name=model.output_dir.name  ,    project=_lowerCamelCase			)

      elif args.logger_name == "wandb_shared":
            from pytorch_lightning.loggers import WandbLogger

            _A     	=      WandbLogger(name=model.output_dir.name  ,    project=F'''hf_{dataset}'''			)

      if args.early_stopping_patience >= 0:
            _A     	=      get_early_stopping_callback(model.val_metric  ,    args.early_stopping_patience			)
      else:
            _A     	=      False

      _A     	=      args.val_metric == "loss"
      _A     	=      generic_train(
          _lowerCamelCase  ,    _lowerCamelCase  ,    logging_callback=SeqaSeqLoggingCallback()  ,    checkpoint_callback=get_checkpoint_callback(
              args.output_dir  ,    model.val_metric  ,    args.save_top_k  ,    _lowerCamelCase			)  ,    early_stopping_callback=_lowerCamelCase  ,    logger=_lowerCamelCase  ,    )
      pickle_save(model.hparams  ,    model.output_dir / "hparams.pkl"			)
      if not args.do_predict:
            return model

      _A     	=      ""
      _A     	=      sorted(glob.glob(os.path.join(args.output_dir  ,    "*.ckpt"			)  ,    recursive=_lowerCamelCase			)			)
      if checkpoints:
            _A     	=      checkpoints[-1]
            _A     	=      checkpoints[-1]
      trainer.logger.log_hyperparams(model.hparams			)

      # test() without a model tests using the best checkpoint automatically
      trainer.test()
      return model


if __name__ == "__main__":
    lowerCamelCase_				   =   argparse.ArgumentParser()
    lowerCamelCase_				   =   pl.Trainer.add_argparse_args(parser)
    lowerCamelCase_				   =   SummarizationModule.add_model_specific_args(parser, os.getcwd())

    lowerCamelCase_				   =   parser.parse_args()

    main(args)













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




