



import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionAttendAndExcitePipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_numpy, skip_mps, slow
from diffusers.utils.testing_utils import require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


_lowerCAmelCase    : Optional[int]							=							False






@skip_mps
class      UpperCAmelCase_  (    _UpperCamelCase	,      _UpperCamelCase	,      _UpperCamelCase	,      unittest.TestCase						):
      __SCREAMING_SNAKE_CASE						:       int								=			StableDiffusionAttendAndExcitePipeline
      __SCREAMING_SNAKE_CASE						:       str								=			False
      __SCREAMING_SNAKE_CASE						:       int								=			TEXT_TO_IMAGE_PARAMS
      __SCREAMING_SNAKE_CASE						:       Optional[int]								=			TEXT_TO_IMAGE_BATCH_PARAMS.union({'token_indices'}						)
      __SCREAMING_SNAKE_CASE						:       str								=			TEXT_TO_IMAGE_IMAGE_PARAMS
      __SCREAMING_SNAKE_CASE						:       Union[str, Any]								=			TEXT_TO_IMAGE_IMAGE_PARAMS



      @classmethod
      def 						snake_case_ (					cls					:     int						):
           super().setUpClass()
           torch.use_deterministic_algorithms(A						)



      @classmethod
      def 						snake_case_ (					cls					:     List[Any]						):
           super().tearDownClass()
           torch.use_deterministic_algorithms(A						)



      def 						snake_case_ (					self					:     str						):
           torch.manual_seed(0						)
           _UpperCAmelCase      :     Tuple        =   UNetaDConditionModel(
               block_out_channels=(3_2, 6_4)					,     layers_per_block=1					,     sample_size=3_2					,     in_channels=4					,     out_channels=4					,     down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")					,     up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")					,     cross_attention_dim=3_2					,     attention_head_dim=(2, 4)					,     use_linear_projection=A					,     )
           _UpperCAmelCase      :     Tuple        =   DDIMScheduler(
               beta_start=0.00_085					,     beta_end=0.012					,     beta_schedule="scaled_linear"					,     clip_sample=A					,     set_alpha_to_one=A					,     )
           torch.manual_seed(0						)
           _UpperCAmelCase      :     Union[str, Any]        =   AutoencoderKL(
               block_out_channels=[3_2, 6_4]					,     in_channels=3					,     out_channels=3					,     down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]					,     up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]					,     latent_channels=4					,     sample_size=1_2_8					,     )
           torch.manual_seed(0						)
           _UpperCAmelCase      :     Dict        =   CLIPTextConfig(
               bos_token_id=0					,     eos_token_id=2					,     hidden_size=3_2					,     intermediate_size=3_7					,     layer_norm_eps=1e-05					,     num_attention_heads=4					,     num_hidden_layers=5					,     pad_token_id=1					,     vocab_size=1_0_0_0					,     hidden_act="gelu"					,     projection_dim=5_1_2					,     )
           _UpperCAmelCase      :     Dict        =   CLIPTextModel(A						)
           _UpperCAmelCase      :     Any        =   CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"						)

           _UpperCAmelCase      :     List[Any]        =   {
               "unet": unet,
               "scheduler": scheduler,
               "vae": vae,
               "text_encoder": text_encoder,
               "tokenizer": tokenizer,
               "safety_checker": None,
               "feature_extractor": None,
           }

           return components



      def 						snake_case_ (					self					:     int					,     A					:     str					,     A					:     int=0						):
           if str(A						).startswith("mps"						):
                _UpperCAmelCase      :     Union[str, Any]        =   torch.manual_seed(A						)
           else:
                _UpperCAmelCase      :     Dict        =   torch.Generator(device=A						).manual_seed(A						)
           _UpperCAmelCase      :     int        =   {
               "prompt": "a cat and a frog",
               "token_indices": [2, 5],
               "generator": generator,
               "num_inference_steps": 1,
               "guidance_scale": 6.0,
               "output_type": "numpy",
               "max_iter_to_alter": 2,
               "thresholds": {0: 0.7},
           }
           return inputs



      def 						snake_case_ (					self					:     List[Any]						):
           _UpperCAmelCase      :     Tuple        =   "cpu"

           _UpperCAmelCase      :     Union[str, Any]        =   self.get_dummy_components()
           _UpperCAmelCase      :     List[Any]        =   self.pipeline_class(**A						)
           pipe.to(A						)
           pipe.set_progress_bar_config(disable=A						)

           _UpperCAmelCase      :     Union[str, Any]        =   self.get_dummy_inputs(A						)
           _UpperCAmelCase      :     int        =   pipe(**A						).images
           _UpperCAmelCase      :     str        =   image[0, -3:, -3:, -1]

           self.assertEqual(image.shape					,     (1, 6_4, 6_4, 3)						)
           _UpperCAmelCase      :     Union[str, Any]        =   np.array(
               [0.63_905_364, 0.62_897_307, 0.48_599_017, 0.5_133_624, 0.5_550_048, 0.45_769_516, 0.50_326_973, 0.5_023_139, 0.45_384_496]						)
           _UpperCAmelCase      :     Union[str, Any]        =   np.abs(image_slice.flatten() - expected_slice						).max()
           self.assertLessEqual(A					,     1e-3						)



      def 						snake_case_ (					self					:     List[Any]						):
           super().test_cpu_offload_forward_pass(expected_max_diff=5e-4						)



      def 						snake_case_ (					self					:     int						):
           # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
           self._test_inference_batch_consistent(batch_sizes=[1, 2]						)



      def 						snake_case_ (					self					:     List[Any]						):
           self._test_inference_batch_single_identical(batch_size=2					,     expected_max_diff=7e-4						)



      def 						snake_case_ (					self					:     Any						):
           super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3						)



      def 						snake_case_ (					self					:     List[str]						):
           super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5e-4						)



      def 						snake_case_ (					self					:     Tuple						):
           super().test_save_load_local(expected_max_difference=5e-4						)



      def 						snake_case_ (					self					:     str						):
           super().test_save_load_optional_components(expected_max_difference=4e-4						)







@require_torch_gpu
@slow
class      UpperCAmelCase_  (    unittest.TestCase						):



      @classmethod
      def 						snake_case_ (					cls					:     Optional[Any]						):
           super().setUpClass()
           torch.use_deterministic_algorithms(A						)



      @classmethod
      def 						snake_case_ (					cls					:     int						):
           super().tearDownClass()
           torch.use_deterministic_algorithms(A						)



      def 						snake_case_ (					self					:     Optional[int]						):
           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()



      def 						snake_case_ (					self					:     List[Any]						):
           _UpperCAmelCase      :     int        =   torch.manual_seed(5_1						)

           _UpperCAmelCase      :     List[Any]        =   StableDiffusionAttendAndExcitePipeline.from_pretrained(
               "CompVis/stable-diffusion-v1-4"					,     safety_checker=A					,     torch_dtype=torch.floataa						)
           pipe.to("cuda"						)

           _UpperCAmelCase      :     int        =   "a painting of an elephant with glasses"
           _UpperCAmelCase      :     Tuple        =   [5, 7]

           _UpperCAmelCase      :     Optional[Any]        =   pipe(
               prompt=A					,     token_indices=A					,     guidance_scale=7.5					,     generator=A					,     num_inference_steps=5					,     max_iter_to_alter=5					,     output_type="numpy"					,     ).images[0]

           _UpperCAmelCase      :     int        =   load_numpy(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy"						)
           assert np.abs((expected_image - image).max()						) < 5e-1





"""simple docstring"""




import argparse
import os
from pathlib import Path
from typing import Dict

import tensorflow as tf
import torch
from tqdm import tqdm

from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer
from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params


_lowerCAmelCase    : List[str]							=							[
    # replace left string with right string to get the relevant state_dict key (identical state dict to bart)
    ["memory_attention", "encoder_attn"],
    ["attention", "attn"],
    ["/", "."],
    [".LayerNorm.gamma", "_layer_norm.weight"],
    [".LayerNorm.beta", "_layer_norm.bias"],
    ["r.layer_", "r.layers."],
    ["output_proj", "out_proj"],
    ["ffn.dense_1.", "fc2."],
    ["ffn.dense.", "fc1."],
    ["ffn_layer_norm", "final_layer_norm"],
    ["kernel", "weight"],
    ["encoder_layer_norm.", "encoder.layer_norm."],
    ["decoder_layer_norm.", "decoder.layer_norm."],
    ["embeddings.weights", "shared.weight"],
]

def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						Dict    )  ->       List[str]:





     '''simple docstring'''

     for pegasus_name, hf_name in PATTERNS:
          _UpperCAmelCase      :     str        =   k.replace(SCREAMING_SNAKE_CASE__						,  SCREAMING_SNAKE_CASE__    )
     return k

def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						dict						,  SCREAMING_SNAKE_CASE__     :						dict    )  ->       PegasusForConditionalGeneration:





     '''simple docstring'''

     _UpperCAmelCase      :     List[Any]        =   DEFAULTS.copy()
     cfg_kwargs.update(SCREAMING_SNAKE_CASE__    )
     _UpperCAmelCase      :     Optional[Any]        =   PegasusConfig(**SCREAMING_SNAKE_CASE__    )
     _UpperCAmelCase      :     Optional[Any]        =   PegasusForConditionalGeneration(SCREAMING_SNAKE_CASE__    )
     _UpperCAmelCase      :     Optional[int]        =   torch_model.model.state_dict()
     _UpperCAmelCase      :     Union[str, Any]        =   {}
     for k, v in tf_weights.items():
          _UpperCAmelCase      :     Union[str, Any]        =   rename_state_dict_key(SCREAMING_SNAKE_CASE__    )
          if new_k not in sd:
               raise ValueError(f'could not find new key {new_k} in state dict. (converted from {k})'    )

          if "dense" in k or "proj" in new_k:
               _UpperCAmelCase      :     Any        =   v.T
          _UpperCAmelCase      :     str        =   torch.tensor(SCREAMING_SNAKE_CASE__						,  dtype=sd[new_k].dtype    )
          assert v.shape == sd[new_k].shape, f'{new_k}, {k}, {v.shape}, {sd[new_k].shape}'
     # make sure embedding.padding_idx is respected
     _UpperCAmelCase      :     Tuple        =   torch.zeros_like(mapping["shared.weight"][cfg.pad_token_id + 1]    )
     _UpperCAmelCase      :     Any        =   mapping["shared.weight"]
     _UpperCAmelCase      :     Dict        =   mapping["shared.weight"]
     _UpperCAmelCase      :     Dict        =   {k: torch.zeros_like(SCREAMING_SNAKE_CASE__    ) for k, v in sd.items() if k.endswith("bias"    ) and k not in mapping}
     mapping.update(**SCREAMING_SNAKE_CASE__    )
     _UpperCAmelCase    ,	_UpperCAmelCase      :     List[Any]        =   torch_model.model.load_state_dict(SCREAMING_SNAKE_CASE__						,  strict=SCREAMING_SNAKE_CASE__    )
     _UpperCAmelCase      :     int        =   [
         k for k in missing if k not in ["encoder.embed_positions.weight", "decoder.embed_positions.weight"]
     ]
     assert unexpected_missing == [], f'no matches found for the following torch keys {unexpected_missing}'
     assert extra == [], f'no matches found for the following tf keys {extra}'
     return torch_model

def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						Dict="./ckpt/aeslc/model.ckpt-32000"    )  ->       Dict:





     '''simple docstring'''

     _UpperCAmelCase      :     Optional[int]        =   tf.train.list_variables(SCREAMING_SNAKE_CASE__    )
     _UpperCAmelCase      :     Union[str, Any]        =   {}
     _UpperCAmelCase      :     Optional[Any]        =   ["Adafactor", "global_step"]
     for name, shape in tqdm(SCREAMING_SNAKE_CASE__						,  desc="converting tf checkpoint to dict"    ):
          _UpperCAmelCase      :     Union[str, Any]        =   any(pat in name for pat in ignore_name    )
          if skip_key:
               continue
          _UpperCAmelCase      :     int        =   tf.train.load_variable(SCREAMING_SNAKE_CASE__						,  SCREAMING_SNAKE_CASE__    )
          _UpperCAmelCase      :     Dict        =   array
     return tf_weights

def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						str						,  SCREAMING_SNAKE_CASE__     :						str    )  ->       Dict:





     '''simple docstring'''

     _UpperCAmelCase      :     Dict        =   Path(SCREAMING_SNAKE_CASE__    ).parent.name
     _UpperCAmelCase      :     Tuple        =   task_specific_params[f'summarization_{dataset}']["max_position_embeddings"]
     _UpperCAmelCase      :     Dict        =   PegasusTokenizer.from_pretrained("sshleifer/pegasus"						,  model_max_length=SCREAMING_SNAKE_CASE__    )
     assert tok.model_max_length == desired_max_model_length
     tok.save_pretrained(SCREAMING_SNAKE_CASE__    )

     # convert model
     _UpperCAmelCase      :     Union[str, Any]        =   get_tf_weights_as_numpy(SCREAMING_SNAKE_CASE__    )
     _UpperCAmelCase      :     Optional[Any]        =   task_specific_params[f'summarization_{dataset}']
     if dataset == "large":
          _UpperCAmelCase      :     Optional[int]        =   task_specific_params
     _UpperCAmelCase      :     str        =   convert_pegasus(SCREAMING_SNAKE_CASE__						,  SCREAMING_SNAKE_CASE__    )
     torch_model.save_pretrained(SCREAMING_SNAKE_CASE__    )
     _UpperCAmelCase      :     Optional[Any]        =   torch_model.state_dict()
     sd.pop("model.decoder.embed_positions.weight"    )
     sd.pop("model.encoder.embed_positions.weight"    )
     torch.save(SCREAMING_SNAKE_CASE__						,  Path(SCREAMING_SNAKE_CASE__    ) / "pytorch_model.bin"    )


if __name__ == "__main__":
 _lowerCAmelCase    : Union[str, Any]							=							argparse.ArgumentParser()
 # Required parameters
 parser.add_argument("tf_ckpt_path", type=str, help="passed to tf.train.list_variables")
 parser.add_argument("save_dir", default=None, type=str, help="Path to the output PyTorch model.")
 _lowerCAmelCase    : Union[str, Any]							=							parser.parse_args()
 if args.save_dir is None:
  _lowerCAmelCase    : Tuple							=							Path(args.tf_ckpt_path).parent.name
  _lowerCAmelCase    : Dict							=							os.path.join("pegasus", dataset)
 convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
