

'''simple docstring'''
import unittest

import numpy as np
import torch

from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device

from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()







class 							A__   (	A__					,       unittest.TestCase  ):
  A__					=    DDIMPipeline
  A__					=    UNCONDITIONAL_IMAGE_GENERATION_PARAMS
  A__					=    PipelineTesterMixin.required_optional_params - {
      'num_images_per_prompt',
      'latents',
      'callback',
      'callback_steps',
  }
  A__					=    UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS
  A__					=    False





  def 						A  (		self				:     List[str]			)     ->   Tuple:





       '''simple docstring'''






       torch.manual_seed(0			)
       _SCREAMING_SNAKE_CASE							   =UNetaDModel(
           block_out_channels=(32, 64)							, layers_per_block=2							, sample_size=32							, in_channels=3							, out_channels=3							, down_block_types=('DownBlock2D', 'AttnDownBlock2D')							, up_block_types=('AttnUpBlock2D', 'UpBlock2D')							, )
       _SCREAMING_SNAKE_CASE							   =DDIMScheduler()
       _SCREAMING_SNAKE_CASE							   ={'unet': unet, 'scheduler': scheduler}
       return components





  def 						A  (		self				:     str							, _a				:     Tuple							, _a				:     str=0			)     ->   Optional[Any]:





       '''simple docstring'''






       if str(_a			).startswith('mps'			):
            _SCREAMING_SNAKE_CASE							   =torch.manual_seed(_a			)
       else:
            _SCREAMING_SNAKE_CASE							   =torch.Generator(device=_a			).manual_seed(_a			)
       _SCREAMING_SNAKE_CASE							   ={
           'batch_size': 1,
           'generator': generator,
           'num_inference_steps': 2,
           'output_type': 'numpy',
       }
       return inputs





  def 						A  (		self				:     int			)     ->   List[str]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   ='cpu'

       _SCREAMING_SNAKE_CASE							   =self.get_dummy_components()
       _SCREAMING_SNAKE_CASE							   =self.pipeline_class(**_a			)
       pipe.to(_a			)
       pipe.set_progress_bar_config(disable=_a			)

       _SCREAMING_SNAKE_CASE							   =self.get_dummy_inputs(_a			)
       _SCREAMING_SNAKE_CASE							   =pipe(**_a			).images
       _SCREAMING_SNAKE_CASE							   =image[0, -3:, -3:, -1]

       self.assertEqual(image.shape							, (1, 32, 32, 3)			)
       _SCREAMING_SNAKE_CASE							   =np.array(
           [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04]			)
       _SCREAMING_SNAKE_CASE							   =np.abs(image_slice.flatten() - expected_slice			).max()
       self.assertLessEqual(_a							, 1e-3			)





  def 						A  (		self				:     Tuple			)     ->   Optional[int]:





       '''simple docstring'''






       super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3			)





  def 						A  (		self				:     List[str]			)     ->   List[Any]:





       '''simple docstring'''






       super().test_save_load_local(expected_max_difference=3e-3			)





  def 						A  (		self				:     Optional[int]			)     ->   Union[str, Any]:





       '''simple docstring'''






       super().test_save_load_optional_components(expected_max_difference=3e-3			)





  def 						A  (		self				:     str			)     ->   Any:





       '''simple docstring'''






       super().test_inference_batch_single_identical(expected_max_diff=3e-3			)







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





  def 						A  (		self				:     List[str]			)     ->   Optional[int]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   ='google/ddpm-cifar10-32'

       _SCREAMING_SNAKE_CASE							   =UNetaDModel.from_pretrained(_a			)
       _SCREAMING_SNAKE_CASE							   =DDIMScheduler()

       _SCREAMING_SNAKE_CASE							   =DDIMPipeline(unet=_a							, scheduler=_a			)
       ddim.to(_a			)
       ddim.set_progress_bar_config(disable=_a			)

       _SCREAMING_SNAKE_CASE							   =torch.manual_seed(0			)
       _SCREAMING_SNAKE_CASE							   =ddim(generator=_a							, eta=0.0							, output_type='numpy'			).images

       _SCREAMING_SNAKE_CASE							   =image[0, -3:, -3:, -1]

       assert image.shape == (1, 32, 32, 3)
       _SCREAMING_SNAKE_CASE							   =np.array([0.17_23, 0.16_17, 0.16_00, 0.16_26, 0.14_97, 0.15_13, 0.15_05, 0.14_42, 0.14_53]			)

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





  def 						A  (		self				:     Optional[Any]			)     ->   Dict:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   ='google/ddpm-ema-bedroom-256'

       _SCREAMING_SNAKE_CASE							   =UNetaDModel.from_pretrained(_a			)
       _SCREAMING_SNAKE_CASE							   =DDIMScheduler.from_pretrained(_a			)

       _SCREAMING_SNAKE_CASE							   =DDIMPipeline(unet=_a							, scheduler=_a			)
       ddpm.to(_a			)
       ddpm.set_progress_bar_config(disable=_a			)

       _SCREAMING_SNAKE_CASE							   =torch.manual_seed(0			)
       _SCREAMING_SNAKE_CASE							   =ddpm(generator=_a							, output_type='numpy'			).images

       _SCREAMING_SNAKE_CASE							   =image[0, -3:, -3:, -1]

       assert image.shape == (1, 256, 256, 3)
       _SCREAMING_SNAKE_CASE							   =np.array([0.00_60, 0.02_01, 0.03_44, 0.00_24, 0.00_18, 0.00_02, 0.00_22, 0.00_00, 0.00_69]			)

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



'''simple docstring'''
import argparse
import io

import requests
import torch
from omegaconf import OmegaConf

from diffusers import AutoencoderKL
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import (
    assign_to_checkpoint,
    conv_attn_to_linear,
    create_vae_diffusers_config,
    renew_vae_attention_paths,
    renew_vae_resnet_paths,
)


def 	_lowerCAmelCase (						_UpperCamelCase						:					Tuple							,			_UpperCamelCase						:					List[Any]    )				->      Dict:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							   =checkpoint

     _SCREAMING_SNAKE_CASE							   ={}

     _SCREAMING_SNAKE_CASE							   =vae_state_dict['encoder.conv_in.weight']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['encoder.conv_in.bias']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['encoder.conv_out.weight']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['encoder.conv_out.bias']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['encoder.norm_out.weight']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['encoder.norm_out.bias']

     _SCREAMING_SNAKE_CASE							   =vae_state_dict['decoder.conv_in.weight']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['decoder.conv_in.bias']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['decoder.conv_out.weight']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['decoder.conv_out.bias']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['decoder.norm_out.weight']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['decoder.norm_out.bias']

     _SCREAMING_SNAKE_CASE							   =vae_state_dict['quant_conv.weight']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['quant_conv.bias']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['post_quant_conv.weight']
     _SCREAMING_SNAKE_CASE							   =vae_state_dict['post_quant_conv.bias']

     # Retrieves the keys for the encoder down blocks only
     _SCREAMING_SNAKE_CASE							   =len({'.'.join(layer.split('.'    )[:3]    ) for layer in vae_state_dict if 'encoder.down' in layer}    )
     _SCREAMING_SNAKE_CASE							   ={
         layer_id: [key for key in vae_state_dict if f"down.{layer_id}" in key] for layer_id in range(_UpperCamelCase    )
     }

     # Retrieves the keys for the decoder up blocks only
     _SCREAMING_SNAKE_CASE							   =len({'.'.join(layer.split('.'    )[:3]    ) for layer in vae_state_dict if 'decoder.up' in layer}    )
     _SCREAMING_SNAKE_CASE							   ={
         layer_id: [key for key in vae_state_dict if f"up.{layer_id}" in key] for layer_id in range(_UpperCamelCase    )
     }

     for i in range(_UpperCamelCase    ):
          _SCREAMING_SNAKE_CASE							   =[key for key in down_blocks[i] if f"down.{i}" in key and f"down.{i}.downsample" not in key]

          if f"encoder.down.{i}.downsample.conv.weight" in vae_state_dict:
               _SCREAMING_SNAKE_CASE							   =vae_state_dict.pop(
                   f"encoder.down.{i}.downsample.conv.weight"    )
               _SCREAMING_SNAKE_CASE							   =vae_state_dict.pop(
                   f"encoder.down.{i}.downsample.conv.bias"    )

          _SCREAMING_SNAKE_CASE							   =renew_vae_resnet_paths(_UpperCamelCase    )
          _SCREAMING_SNAKE_CASE							   ={'old': f"down.{i}.block", 'new': f"down_blocks.{i}.resnets"}
          assign_to_checkpoint(_UpperCamelCase							,			_UpperCamelCase							,			_UpperCamelCase							,			additional_replacements=[meta_path]							,			config=_UpperCamelCase    )

     _SCREAMING_SNAKE_CASE							   =[key for key in vae_state_dict if 'encoder.mid.block' in key]
     _SCREAMING_SNAKE_CASE							   =2
     for i in range(1							,			num_mid_res_blocks + 1    ):
          _SCREAMING_SNAKE_CASE							   =[key for key in mid_resnets if f"encoder.mid.block_{i}" in key]

          _SCREAMING_SNAKE_CASE							   =renew_vae_resnet_paths(_UpperCamelCase    )
          _SCREAMING_SNAKE_CASE							   ={'old': f"mid.block_{i}", 'new': f"mid_block.resnets.{i - 1}"}
          assign_to_checkpoint(_UpperCamelCase							,			_UpperCamelCase							,			_UpperCamelCase							,			additional_replacements=[meta_path]							,			config=_UpperCamelCase    )

     _SCREAMING_SNAKE_CASE							   =[key for key in vae_state_dict if 'encoder.mid.attn' in key]
     _SCREAMING_SNAKE_CASE							   =renew_vae_attention_paths(_UpperCamelCase    )
     _SCREAMING_SNAKE_CASE							   ={'old': 'mid.attn_1', 'new': 'mid_block.attentions.0'}
     assign_to_checkpoint(_UpperCamelCase							,			_UpperCamelCase							,			_UpperCamelCase							,			additional_replacements=[meta_path]							,			config=_UpperCamelCase    )
     conv_attn_to_linear(_UpperCamelCase    )

     for i in range(_UpperCamelCase    ):
          _SCREAMING_SNAKE_CASE							   =num_up_blocks - 1 - i
          _SCREAMING_SNAKE_CASE							   =[
              key for key in up_blocks[block_id] if f"up.{block_id}" in key and f"up.{block_id}.upsample" not in key
          ]

          if f"decoder.up.{block_id}.upsample.conv.weight" in vae_state_dict:
               _SCREAMING_SNAKE_CASE							   =vae_state_dict[
                   f"decoder.up.{block_id}.upsample.conv.weight"
               ]
               _SCREAMING_SNAKE_CASE							   =vae_state_dict[
                   f"decoder.up.{block_id}.upsample.conv.bias"
               ]

          _SCREAMING_SNAKE_CASE							   =renew_vae_resnet_paths(_UpperCamelCase    )
          _SCREAMING_SNAKE_CASE							   ={'old': f"up.{block_id}.block", 'new': f"up_blocks.{i}.resnets"}
          assign_to_checkpoint(_UpperCamelCase							,			_UpperCamelCase							,			_UpperCamelCase							,			additional_replacements=[meta_path]							,			config=_UpperCamelCase    )

     _SCREAMING_SNAKE_CASE							   =[key for key in vae_state_dict if 'decoder.mid.block' in key]
     _SCREAMING_SNAKE_CASE							   =2
     for i in range(1							,			num_mid_res_blocks + 1    ):
          _SCREAMING_SNAKE_CASE							   =[key for key in mid_resnets if f"decoder.mid.block_{i}" in key]

          _SCREAMING_SNAKE_CASE							   =renew_vae_resnet_paths(_UpperCamelCase    )
          _SCREAMING_SNAKE_CASE							   ={'old': f"mid.block_{i}", 'new': f"mid_block.resnets.{i - 1}"}
          assign_to_checkpoint(_UpperCamelCase							,			_UpperCamelCase							,			_UpperCamelCase							,			additional_replacements=[meta_path]							,			config=_UpperCamelCase    )

     _SCREAMING_SNAKE_CASE							   =[key for key in vae_state_dict if 'decoder.mid.attn' in key]
     _SCREAMING_SNAKE_CASE							   =renew_vae_attention_paths(_UpperCamelCase    )
     _SCREAMING_SNAKE_CASE							   ={'old': 'mid.attn_1', 'new': 'mid_block.attentions.0'}
     assign_to_checkpoint(_UpperCamelCase							,			_UpperCamelCase							,			_UpperCamelCase							,			additional_replacements=[meta_path]							,			config=_UpperCamelCase    )
     conv_attn_to_linear(_UpperCamelCase    )
     return new_checkpoint


def 	_lowerCAmelCase (						_UpperCamelCase						:					str							,			_UpperCamelCase						:					str							,			)				->      List[Any]:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							   =requests.get(
         ' https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml'    )
     _SCREAMING_SNAKE_CASE							   =io.BytesIO(r.content    )

     _SCREAMING_SNAKE_CASE							   =OmegaConf.load(_UpperCamelCase    )
     _SCREAMING_SNAKE_CASE							   =5_12
     _SCREAMING_SNAKE_CASE							   ='cuda' if torch.cuda.is_available() else 'cpu'
     if checkpoint_path.endswith('safetensors'    ):
          from safetensors import safe_open

          _SCREAMING_SNAKE_CASE							   ={}
          with safe_open(_UpperCamelCase							,			framework='pt'							,			device='cpu'    ) as f:
               for key in f.keys():
                    _SCREAMING_SNAKE_CASE							   =f.get_tensor(_UpperCamelCase    )
     else:
          _SCREAMING_SNAKE_CASE							   =torch.load(_UpperCamelCase							,			map_location=_UpperCamelCase    )['state_dict']

     # Convert the VAE model.
     _SCREAMING_SNAKE_CASE							   =create_vae_diffusers_config(_UpperCamelCase							,			image_size=_UpperCamelCase    )
     _SCREAMING_SNAKE_CASE							   =custom_convert_ldm_vae_checkpoint(_UpperCamelCase							,			_UpperCamelCase    )

     _SCREAMING_SNAKE_CASE							   =AutoencoderKL(**_UpperCamelCase    )
     vae.load_state_dict(_UpperCamelCase    )
     vae.save_pretrained(_UpperCamelCase    )


if __name__ == "__main__":
     lowerCamelCase			:				Union[str, Any] 			=					argparse.ArgumentParser()

     parser.add_argument("--vae_pt_path", default=None, type=str, required=True, help="Path to the VAE.pt to convert.")
     parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the VAE.pt to convert.")

     lowerCamelCase			:				List[str] 			=					parser.parse_args()

     vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)
