


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_						:		List[Any] ,  UpperCAmelCase_						:		Optional[int]						):




      """simple docstring"""





      a						:Tuple 							=       checkpoint

      a						:List[str] 							=       {}

      a						:Any 							=       vae_state_dict['''encoder.conv_in.weight''']
      a						:List[Any] 							=       vae_state_dict['''encoder.conv_in.bias''']
      a						:Any 							=       vae_state_dict['''encoder.conv_out.weight''']
      a						:str 							=       vae_state_dict['''encoder.conv_out.bias''']
      a						:int 							=       vae_state_dict['''encoder.norm_out.weight''']
      a						:List[str] 							=       vae_state_dict['''encoder.norm_out.bias''']

      a						:Optional[int] 							=       vae_state_dict['''decoder.conv_in.weight''']
      a						:int 							=       vae_state_dict['''decoder.conv_in.bias''']
      a						:List[str] 							=       vae_state_dict['''decoder.conv_out.weight''']
      a						:Any 							=       vae_state_dict['''decoder.conv_out.bias''']
      a						:Optional[Any] 							=       vae_state_dict['''decoder.norm_out.weight''']
      a						:Optional[int] 							=       vae_state_dict['''decoder.norm_out.bias''']

      a						:List[Any] 							=       vae_state_dict['''quant_conv.weight''']
      a						:Optional[Any] 							=       vae_state_dict['''quant_conv.bias''']
      a						:Union[str, Any] 							=       vae_state_dict['''post_quant_conv.weight''']
      a						:str 							=       vae_state_dict['''post_quant_conv.bias''']

      # Retrieves the keys for the encoder down blocks only
      a						:str 							=       len({'''.'''.join(layer.split('''.'''						)[:3]						) for layer in vae_state_dict if '''encoder.down''' in layer}						)
      a						:List[Any] 							=       {
          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
      a						:int 							=       len({'''.'''.join(layer.split('''.'''						)[:3]						) for layer in vae_state_dict if '''decoder.up''' in layer}						)
      a						:Tuple 							=       {
          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_						):
            a						:Optional[Any] 							=       [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:
                  a						:str 							=       vae_state_dict.pop(
                      F'''encoder.down.{i}.downsample.conv.weight'''						)
                  a						:Any 							=       vae_state_dict.pop(
                      F'''encoder.down.{i}.downsample.conv.bias'''						)

            a						:List[str] 							=       renew_vae_resnet_paths(UpperCAmelCase_						)
            a						:Union[str, Any] 							=       {'''old''': F'''down.{i}.block''', '''new''': F'''down_blocks.{i}.resnets'''}
            assign_to_checkpoint(UpperCAmelCase_ ,  UpperCAmelCase_ ,  UpperCAmelCase_ ,  additional_replacements=[meta_path] ,  config=UpperCAmelCase_						)

      a						:int 							=       [key for key in vae_state_dict if '''encoder.mid.block''' in key]
      a						:Optional[int] 							=       2
      for i in range(1 ,  num_mid_res_blocks + 1						):
            a						:List[str] 							=       [key for key in mid_resnets if F'''encoder.mid.block_{i}''' in key]

            a						:Any 							=       renew_vae_resnet_paths(UpperCAmelCase_						)
            a						:Any 							=       {'''old''': F'''mid.block_{i}''', '''new''': F'''mid_block.resnets.{i - 1}'''}
            assign_to_checkpoint(UpperCAmelCase_ ,  UpperCAmelCase_ ,  UpperCAmelCase_ ,  additional_replacements=[meta_path] ,  config=UpperCAmelCase_						)

      a						:Tuple 							=       [key for key in vae_state_dict if '''encoder.mid.attn''' in key]
      a						:int 							=       renew_vae_attention_paths(UpperCAmelCase_						)
      a						:Dict 							=       {'''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_						):
            a						:Tuple 							=       num_up_blocks - 1 - i
            a						:Dict 							=       [
                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:
                  a						:int 							=       vae_state_dict[
                      F'''decoder.up.{block_id}.upsample.conv.weight'''
                  ]
                  a						:Optional[int] 							=       vae_state_dict[
                      F'''decoder.up.{block_id}.upsample.conv.bias'''
                  ]

            a						:Optional[int] 							=       renew_vae_resnet_paths(UpperCAmelCase_						)
            a						:Tuple 							=       {'''old''': F'''up.{block_id}.block''', '''new''': F'''up_blocks.{i}.resnets'''}
            assign_to_checkpoint(UpperCAmelCase_ ,  UpperCAmelCase_ ,  UpperCAmelCase_ ,  additional_replacements=[meta_path] ,  config=UpperCAmelCase_						)

      a						:List[str] 							=       [key for key in vae_state_dict if '''decoder.mid.block''' in key]
      a						:Optional[Any] 							=       2
      for i in range(1 ,  num_mid_res_blocks + 1						):
            a						:int 							=       [key for key in mid_resnets if F'''decoder.mid.block_{i}''' in key]

            a						:Optional[int] 							=       renew_vae_resnet_paths(UpperCAmelCase_						)
            a						:List[Any] 							=       {'''old''': F'''mid.block_{i}''', '''new''': F'''mid_block.resnets.{i - 1}'''}
            assign_to_checkpoint(UpperCAmelCase_ ,  UpperCAmelCase_ ,  UpperCAmelCase_ ,  additional_replacements=[meta_path] ,  config=UpperCAmelCase_						)

      a						:Optional[int] 							=       [key for key in vae_state_dict if '''decoder.mid.attn''' in key]
      a						:List[Any] 							=       renew_vae_attention_paths(UpperCAmelCase_						)
      a						:Optional[Any] 							=       {'''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 ,  ):




      """simple docstring"""





      a						:List[Any] 							=       requests.get(
          ''' https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml'''						)
      a						:Tuple 							=       io.BytesIO(r.content						)

      a						:Any 							=       OmegaConf.load(UpperCAmelCase_						)
      a						:Any 							=       512
      a						:Optional[Any] 							=       '''cuda''' if torch.cuda.is_available() else '''cpu'''
      if checkpoint_path.endswith('''safetensors'''						):
            from safetensors import safe_open

            a						:List[str] 							=       {}
            with safe_open(UpperCAmelCase_ ,  framework='''pt''' ,  device='''cpu'''						) as f:
                  for key in f.keys():
                        a						:Union[str, Any] 							=       f.get_tensor(UpperCAmelCase_						)
      else:
            a						:Dict 							=       torch.load(UpperCAmelCase_ ,  map_location=UpperCAmelCase_						)['''state_dict''']

      # Convert the VAE model.
      a						:List[str] 							=       create_vae_diffusers_config(UpperCAmelCase_ ,  image_size=UpperCAmelCase_						)
      a						:Dict 							=       custom_convert_ldm_vae_checkpoint(UpperCAmelCase_ ,  UpperCAmelCase_						)

      a						:Tuple 							=       AutoencoderKL(**UpperCAmelCase_						)
      vae.load_state_dict(UpperCAmelCase_						)
      vae.save_pretrained(UpperCAmelCase_						)


if __name__ == "__main__":
     snake_case				:    List[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.''')

     snake_case				:    Any       				=     parser.parse_args()

     vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)









def 				__lowerCamelCase						( UpperCAmelCase_						:		int ,  UpperCAmelCase_						:		int						):




      """simple docstring"""





      while b:
            a							,				a						:Optional[Any] 							=       b, a % b
      return a
def 				__lowerCamelCase						( UpperCAmelCase_						:		int ,  UpperCAmelCase_						:		int						):




      """simple docstring"""





      return a if b == 0 else euclidean_gcd_recursive(UpperCAmelCase_ ,  a % b						)
def 				__lowerCamelCase						( ):




      """simple docstring"""





      print(F'''euclidean_gcd(3, 5) = {euclidean_gcd(3 ,  5						)}'''						)
      print(F'''euclidean_gcd(5, 3) = {euclidean_gcd(5 ,  3						)}'''						)
      print(F'''euclidean_gcd(1, 3) = {euclidean_gcd(1 ,  3						)}'''						)
      print(F'''euclidean_gcd(3, 6) = {euclidean_gcd(3 ,  6						)}'''						)
      print(F'''euclidean_gcd(6, 3) = {euclidean_gcd(6 ,  3						)}'''						)

      print(F'''euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3 ,  5						)}'''						)
      print(F'''euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5 ,  3						)}'''						)
      print(F'''euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1 ,  3						)}'''						)
      print(F'''euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3 ,  6						)}'''						)
      print(F'''euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6 ,  3						)}'''						)


if __name__ == "__main__":
     main()





