






"""simple docstring"""




import gc
import random
import unittest

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

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()




class     _lowerCAmelCase(	UpperCAmelCase_							,     UpperCAmelCase_							,     unittest.TestCase ):





       """simple docstring"""







       a    :		Optional[Any]									=StableDiffusionXLImgaImgPipeline
       a    :		Union[str, Any]									=TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""}
       a    :		List[Any]									=PipelineTesterMixin.required_optional_params - {"""latents"""}
       a    :		Any									=TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
       a    :		Tuple									=IMAGE_TO_IMAGE_IMAGE_PARAMS
       a    :		Optional[int]									=IMAGE_TO_IMAGE_IMAGE_PARAMS





       def       _a   ( self							):
         torch.manual_seed(0							)
         UpperCamelCase_: List[Any]   				=    UNetaDConditionModel(
             block_out_channels=(3_2, 6_4)  ,      layers_per_block=2  ,      sample_size=3_2  ,      in_channels=4  ,      out_channels=4  ,      down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')  ,      up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')  ,      attention_head_dim=(2, 4)  ,      use_linear_projection=_lowercase  ,      addition_embed_type='text_time'  ,      addition_time_embed_dim=8  ,      transformer_layers_per_block=(1, 2)  ,      projection_class_embeddings_input_dim=8_0  ,      cross_attention_dim=6_4  ,      )
         UpperCamelCase_: List[Any]   				=    EulerDiscreteScheduler(
             beta_start=0.0_0_0_8_5  ,      beta_end=0.0_1_2  ,      steps_offset=1  ,      beta_schedule='scaled_linear'  ,      timestep_spacing='leading'  ,      )
         torch.manual_seed(0							)
         UpperCamelCase_: List[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_: List[Any]   				=    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=3_2  ,      )
         UpperCamelCase_: Optional[Any]   				=    CLIPTextModel(_lowercase							)
         UpperCamelCase_: Optional[Any]   				=    CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'  ,      local_files_only=_lowercase							)

         UpperCamelCase_: Dict   				=    CLIPTextModelWithProjection(_lowercase							)
         UpperCamelCase_: List[Any]   				=    CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'  ,      local_files_only=_lowercase							)

         UpperCamelCase_: List[str]   				=    {
             'unet': unet,
             'scheduler': scheduler,
             'vae': vae,
             'text_encoder': text_encoder,
             'tokenizer': tokenizer,
             'text_encoder_2': text_encoder_a,
             'tokenizer_2': tokenizer_a,
             # "safety_checker": None,
             # "feature_extractor": None,
         }
         return components





       def       _a   ( self  ,      _lowerCamelCase  ,      _lowerCamelCase=0							):
         UpperCamelCase_: int   				=    floats_tensor((1, 3, 3_2, 3_2)  ,      rng=random.Random(_lowercase							)							).to(_lowercase							)
         UpperCamelCase_: Union[str, Any]   				=    image / 2 + 0.5
         if str(_lowercase							).startswith('mps'							):
           UpperCamelCase_: List[Any]   				=    torch.manual_seed(_lowercase							)
         else:
           UpperCamelCase_: str   				=    torch.Generator(device=_lowercase							).manual_seed(_lowercase							)
         UpperCamelCase_: Dict   				=    {
             'prompt': 'A painting of a squirrel eating a burger',
             'image': image,
             'generator': generator,
             'num_inference_steps': 2,
             'guidance_scale': 5.0,
             'output_type': 'numpy',
             'strength': 0.7_5,
         }
         return inputs





       def       _a   ( self							):
         UpperCamelCase_: Any   				=    'cpu'  # ensure determinism for the device-dependent torch.Generator
         UpperCamelCase_: List[str]   				=    self.get_dummy_components()
         UpperCamelCase_: Union[str, Any]   				=    StableDiffusionXLImgaImgPipeline(**_lowercase							)
         UpperCamelCase_: Any   				=    sd_pipe.to(_lowercase							)
         sd_pipe.set_progress_bar_config(disable=_lowercase							)

         UpperCamelCase_: str   				=    self.get_dummy_inputs(_lowercase							)
         UpperCamelCase_: Optional[int]   				=    sd_pipe(**_lowercase							).images
         UpperCamelCase_: Tuple   				=    image[0, -3:, -3:, -1]

         assert image.shape == (1, 3_2, 3_2, 3)

         UpperCamelCase_: List[str]   				=    np.array([0.4_6_5_6, 0.4_8_4_0, 0.4_4_3_9, 0.6_6_9_8, 0.5_5_7_4, 0.4_5_2_4, 0.5_7_9_9, 0.5_9_4_3, 0.5_1_6_5]							)

         assert np.abs(image_slice.flatten() - expected_slice							).max() < 1e-2





       def       _a   ( self							):
         super().test_attention_slicing_forward_pass(expected_max_diff=3e-3							)





       def       _a   ( self							):
         super().test_inference_batch_single_identical(expected_max_diff=3e-3							)





       def       _a   ( self							):
         pass





       def       _a   ( self							):
         UpperCamelCase_: Optional[Any]   				=    self.get_dummy_components()
         UpperCamelCase_: Optional[int]   				=    StableDiffusionXLImgaImgPipeline(**_lowercase							)
         UpperCamelCase_: Union[str, Any]   				=    sd_pipe.to(_lowercase							)
         UpperCamelCase_: List[Any]   				=    sd_pipe.to(_lowercase							)
         sd_pipe.set_progress_bar_config(disable=_lowercase							)

         # forward without prompt embeds
         UpperCamelCase_: Union[str, Any]   				=    self.get_dummy_inputs(_lowercase							)
         UpperCamelCase_: Union[str, Any]   				=    3 * ['this is a negative prompt']
         UpperCamelCase_: str   				=    negative_prompt
         UpperCamelCase_: Any   				=    3 * [inputs['prompt']]

         UpperCamelCase_: Dict   				=    sd_pipe(**_lowercase							)
         UpperCamelCase_: Tuple   				=    output.images[0, -3:, -3:, -1]

         # forward with prompt embeds
         UpperCamelCase_: List[Any]   				=    self.get_dummy_inputs(_lowercase							)
         UpperCamelCase_: Dict   				=    3 * ['this is a negative prompt']
         UpperCamelCase_: Union[str, Any]   				=    3 * [inputs.pop('prompt'							)]

         (
             (
             UpperCamelCase_   
         )				,(
             UpperCamelCase_   
         )				,(
             UpperCamelCase_   
         )				,(
             UpperCamelCase_   
         )				,   
         ): Tuple   				=    sd_pipe.encode_prompt(_lowercase  ,      negative_prompt=_lowercase							)

         UpperCamelCase_: Dict   				=    sd_pipe(
             **_lowercase  ,      prompt_embeds=_lowercase  ,      negative_prompt_embeds=_lowercase  ,      pooled_prompt_embeds=_lowercase  ,      negative_pooled_prompt_embeds=_lowercase  ,      )
         UpperCamelCase_: int   				=    output.images[0, -3:, -3:, -1]

         # make sure that it's equal
         assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()							).max() < 1e-4







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





       """simple docstring"""







       def       _a   ( self							):
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()





       def       _a   ( self  ,      _lowerCamelCase  ,      _lowerCamelCase="cpu"  ,      _lowerCamelCase=torch.floataa  ,      _lowerCamelCase=0							):
         UpperCamelCase_: Union[str, Any]   				=    torch.Generator(device=_lowercase							).manual_seed(_lowercase							)
         UpperCamelCase_: Dict   				=    np.random.RandomState(_lowercase							).standard_normal((1, 4, 6_4, 6_4)							)
         UpperCamelCase_: Dict   				=    torch.from_numpy(_lowercase							).to(device=_lowercase  ,      dtype=_lowercase							)
         UpperCamelCase_: int   				=    {
             'prompt': 'a photograph of an astronaut riding a horse',
             'latents': latents,
             'generator': generator,
             'num_inference_steps': 3,
             'guidance_scale': 7.5,
             'output_type': 'numpy',
         }
         return inputs





       def       _a   ( self							):
         UpperCamelCase_: List[Any]   				=    DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base'							)
         pipe.to(_lowercase							)
         pipe.set_progress_bar_config(disable=_lowercase							)

         UpperCamelCase_: Union[str, Any]   				=    self.get_inputs(_lowercase							)
         UpperCamelCase_: int   				=    pipe(**_lowercase							).images
         UpperCamelCase_: int   				=    image[0, -3:, -3:, -1].flatten()

         assert image.shape == (1, 5_1_2, 5_1_2, 3)
         UpperCamelCase_: str   				=    np.array([0.4_9_4_9_3, 0.4_7_8_9_6, 0.4_0_7_9_8, 0.5_4_2_1_4, 0.5_3_2_1_2, 0.4_8_2_0_2, 0.4_7_6_5_6, 0.4_6_3_2_9, 0.4_8_5_0_6]							)
         assert np.abs(image_slice - expected_slice							).max() < 7e-3







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


A_		:		Tuple		     =			[
    # 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 (UpperCAmelCase__  )	->    str:
  for pegasus_name, hf_name in PATTERNS:
    UpperCamelCase_: List[str]   				=    k.replace(UpperCAmelCase__     ,   UpperCAmelCase__  )
  return k

def   snake_case (UpperCAmelCase__     ,   UpperCAmelCase__  )	->    PegasusForConditionalGeneration:
  UpperCamelCase_: List[str]   				=    DEFAULTS.copy()
  cfg_kwargs.update(UpperCAmelCase__  )
  UpperCamelCase_: Tuple   				=    PegasusConfig(**UpperCAmelCase__  )
  UpperCamelCase_: Tuple   				=    PegasusForConditionalGeneration(UpperCAmelCase__  )
  UpperCamelCase_: List[Any]   				=    torch_model.model.state_dict()
  UpperCamelCase_: str   				=    {}
  for k, v in tf_weights.items():
    UpperCamelCase_: Dict   				=    rename_state_dict_key(UpperCAmelCase__  )
    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_: int   				=    v.T
    UpperCamelCase_: Union[str, Any]   				=    torch.tensor(UpperCAmelCase__     ,   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_: int   				=    mapping['shared.weight']
  UpperCamelCase_: Union[str, Any]   				=    mapping['shared.weight']
  UpperCamelCase_: Dict   				=    {k: torch.zeros_like(UpperCAmelCase__  ) for k, v in sd.items() if k.endswith('bias'  ) and k not in mapping}
  mapping.update(**UpperCAmelCase__  )
  UpperCamelCase_				,UpperCamelCase_: Optional[int]   				=    torch_model.model.load_state_dict(UpperCAmelCase__     ,   strict=UpperCAmelCase__  )
  UpperCamelCase_: List[str]   				=    [
      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 (UpperCAmelCase__="./ckpt/aeslc/model.ckpt-32000"  )	->    Dict:
  UpperCamelCase_: Union[str, Any]   				=    tf.train.list_variables(UpperCAmelCase__  )
  UpperCamelCase_: Tuple   				=    {}
  UpperCamelCase_: Dict   				=    ['Adafactor', 'global_step']
  for name, shape in tqdm(UpperCAmelCase__     ,   desc='converting tf checkpoint to dict'  ):
    UpperCamelCase_: Union[str, Any]   				=    any(pat in name for pat in ignore_name  )
    if skip_key:
      continue
    UpperCamelCase_: Dict   				=    tf.train.load_variable(UpperCAmelCase__     ,   UpperCAmelCase__  )
    UpperCamelCase_: Optional[Any]   				=    array
  return tf_weights

def   snake_case (UpperCAmelCase__     ,   UpperCAmelCase__  )	->    int:
  # save tokenizer first
  UpperCamelCase_: Any   				=    Path(UpperCAmelCase__  ).parent.name
  UpperCamelCase_: Tuple   				=    task_specific_params[F'''summarization_{dataset}''']['max_position_embeddings']
  UpperCamelCase_: Optional[Any]   				=    PegasusTokenizer.from_pretrained('sshleifer/pegasus'     ,   model_max_length=UpperCAmelCase__  )
  assert tok.model_max_length == desired_max_model_length
  tok.save_pretrained(UpperCAmelCase__  )

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


if __name__ == "__main__":
   A_		:		str		     =			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.')
   A_		:		Optional[Any]		     =			parser.parse_args()
   if args.save_dir is None:
      A_		:		Union[str, Any]		     =			Path(args.tf_ckpt_path).parent.name
      A_		:		Optional[Any]		     =			os.path.join('pegasus', dataset)
   convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)