





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:			Union[str, Any]		,   __UpperCAmelCase:			Dict      )      ->	Union[str, Any]:
    UpperCamelCase__							:				Optional[Any]          =      checkpoint

    UpperCamelCase__							:				int          =      {}

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

    UpperCamelCase__							:				Tuple          =      vae_state_dict['''decoder.conv_in.weight''']
    UpperCamelCase__							:				Dict          =      vae_state_dict['''decoder.conv_in.bias''']
    UpperCamelCase__							:				Union[str, Any]          =      vae_state_dict['''decoder.conv_out.weight''']
    UpperCamelCase__							:				Tuple          =      vae_state_dict['''decoder.conv_out.bias''']
    UpperCamelCase__							:				List[str]          =      vae_state_dict['''decoder.norm_out.weight''']
    UpperCamelCase__							:				Optional[int]          =      vae_state_dict['''decoder.norm_out.bias''']

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

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

        UpperCamelCase__							:				List[str]          =      renew_vae_resnet_paths(__UpperCAmelCase      )
        UpperCamelCase__							:				int          =      {'''old''': f"down.{i}.block", '''new''': f"down_blocks.{i}.resnets"}
        assign_to_checkpoint(__UpperCAmelCase		,   __UpperCAmelCase		,   __UpperCAmelCase		,   additional_replacements=[meta_path]		,   config=__UpperCAmelCase      )

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

        UpperCamelCase__							:				Tuple          =      renew_vae_resnet_paths(__UpperCAmelCase      )
        UpperCamelCase__							:				List[str]          =      {'''old''': f"mid.block_{i}", '''new''': f"mid_block.resnets.{i - 1}"}
        assign_to_checkpoint(__UpperCAmelCase		,   __UpperCAmelCase		,   __UpperCAmelCase		,   additional_replacements=[meta_path]		,   config=__UpperCAmelCase      )

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

        UpperCamelCase__							:				Any          =      renew_vae_resnet_paths(__UpperCAmelCase      )
        UpperCamelCase__							:				Union[str, Any]          =      {'''old''': f"up.{block_id}.block", '''new''': f"up_blocks.{i}.resnets"}
        assign_to_checkpoint(__UpperCAmelCase		,   __UpperCAmelCase		,   __UpperCAmelCase		,   additional_replacements=[meta_path]		,   config=__UpperCAmelCase      )

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

        UpperCamelCase__							:				Optional[Any]          =      renew_vae_resnet_paths(__UpperCAmelCase      )
        UpperCamelCase__							:				str          =      {'''old''': f"mid.block_{i}", '''new''': f"mid_block.resnets.{i - 1}"}
        assign_to_checkpoint(__UpperCAmelCase		,   __UpperCAmelCase		,   __UpperCAmelCase		,   additional_replacements=[meta_path]		,   config=__UpperCAmelCase      )

    UpperCamelCase__							:				Union[str, Any]          =      [key for key in vae_state_dict if '''decoder.mid.attn''' in key]
    UpperCamelCase__							:				str          =      renew_vae_attention_paths(__UpperCAmelCase      )
    UpperCamelCase__							:				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		,   )      ->	List[Any]:
    # Only support V1
    UpperCamelCase__							:				Optional[Any]          =      requests.get(
        ''' https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml'''      )
    UpperCamelCase__							:				Tuple          =      io.BytesIO(r.content      )

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

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

    # Convert the VAE model.
    UpperCamelCase__							:				Dict          =      create_vae_diffusers_config(__UpperCAmelCase		,   image_size=__UpperCAmelCase      )
    UpperCamelCase__							:				Optional[int]          =      custom_convert_ldm_vae_checkpoint(__UpperCAmelCase		,   __UpperCAmelCase      )

    UpperCamelCase__							:				Optional[Any]          =      AutoencoderKL(**__UpperCAmelCase      )
    vae.load_state_dict(__UpperCAmelCase      )
    vae.save_pretrained(__UpperCAmelCase      )


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

  UpperCAmelCase_     							= parser.parse_args()

  vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)








from typing import List, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase_     							= logging.get_logger(__name__)

UpperCAmelCase_     							= {
    'huggingface/informer-tourism-monthly': (
        'https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json'
    ),
    # See all Informer models at https://huggingface.co/models?filter=informer
}






class     lowercase__       (	__lowerCamelCase				):

   '''simple docstring'''


   a						:							Optional[int]   		=		"informer"
   a						:							Tuple   		=		{
       "hidden_size": "d_model",
       "num_attention_heads": "encoder_attention_heads",
       "num_hidden_layers": "encoder_layers",
   }




   def __init__(    self,		__magic_name__ = None,		__magic_name__ = None,		__magic_name__ = "student_t",		__magic_name__ = "nll",		__magic_name__ = 1,		__magic_name__ = None,		__magic_name__ = "mean",		__magic_name__ = 0,		__magic_name__ = 0,		__magic_name__ = 0,		__magic_name__ = 0,		__magic_name__ = None,		__magic_name__ = None,		__magic_name__ = 64,		__magic_name__ = 32,		__magic_name__ = 32,		__magic_name__ = 2,		__magic_name__ = 2,		__magic_name__ = 2,		__magic_name__ = 2,		__magic_name__ = True,		__magic_name__ = "gelu",		__magic_name__ = 0.05,		__magic_name__ = 0.1,		__magic_name__ = 0.1,		__magic_name__ = 0.1,		__magic_name__ = 0.1,		__magic_name__ = 100,		__magic_name__ = 0.02,		__magic_name__=True,		__magic_name__ = "prob",		__magic_name__ = 5,		__magic_name__ = True,		**__magic_name__,		) ->      Optional[int]:






       """simple docstring"""
       # time series specific configuration
       UpperCamelCase__							:				List[Any]          =      prediction_length
       UpperCamelCase__							:				Any          =      context_length or prediction_length
       UpperCamelCase__							:				Optional[int]          =      distribution_output
       UpperCamelCase__							:				Union[str, Any]          =      loss
       UpperCamelCase__							:				Optional[Any]          =      input_size
       UpperCamelCase__							:				Dict          =      num_time_features
       UpperCamelCase__							:				Dict          =      lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7]
       UpperCamelCase__							:				Optional[int]          =      scaling
       UpperCamelCase__							:				Any          =      num_dynamic_real_features
       UpperCamelCase__							:				Optional[int]          =      num_static_real_features
       UpperCamelCase__							:				Optional[Any]          =      num_static_categorical_features

       # set cardinality
       if cardinality and num_static_categorical_features > 0:
           if len(__magic_name__							) != num_static_categorical_features:
               raise ValueError(
                   '''The cardinality should be a list of the same length as `num_static_categorical_features`'''							)
           UpperCamelCase__							:				str          =      cardinality
       else:
           UpperCamelCase__							:				int          =      [0]

       # set embedding_dimension
       if embedding_dimension and num_static_categorical_features > 0:
           if len(__magic_name__							) != num_static_categorical_features:
               raise ValueError(
                   '''The embedding dimension should be a list of the same length as `num_static_categorical_features`'''							)
           UpperCamelCase__							:				Any          =      embedding_dimension
       else:
           UpperCamelCase__							:				Union[str, Any]          =      [min(50,		(cat + 1) // 2							) for cat in self.cardinality]

       UpperCamelCase__							:				Optional[Any]          =      num_parallel_samples

       # Transformer architecture configuration
       UpperCamelCase__							:				Union[str, Any]          =      input_size * len(self.lags_sequence							) + self._number_of_features
       UpperCamelCase__							:				Optional[Any]          =      d_model
       UpperCamelCase__							:				Tuple          =      encoder_attention_heads
       UpperCamelCase__							:				Any          =      decoder_attention_heads
       UpperCamelCase__							:				Dict          =      encoder_ffn_dim
       UpperCamelCase__							:				Optional[Any]          =      decoder_ffn_dim
       UpperCamelCase__							:				str          =      encoder_layers
       UpperCamelCase__							:				Optional[int]          =      decoder_layers

       UpperCamelCase__							:				Optional[Any]          =      dropout
       UpperCamelCase__							:				List[Any]          =      attention_dropout
       UpperCamelCase__							:				Any          =      activation_dropout
       UpperCamelCase__							:				Optional[int]          =      encoder_layerdrop
       UpperCamelCase__							:				Union[str, Any]          =      decoder_layerdrop

       UpperCamelCase__							:				Tuple          =      activation_function
       UpperCamelCase__							:				List[str]          =      init_std

       UpperCamelCase__							:				int          =      use_cache

       # Informer
       UpperCamelCase__							:				Optional[int]          =      attention_type
       UpperCamelCase__							:				Optional[int]          =      sampling_factor
       UpperCamelCase__							:				Dict          =      distil

       super().__init__(is_encoder_decoder=__magic_name__,		**__magic_name__							)




   @property
   def       UpperCamelCase__  (    self							) ->      int:






       """simple docstring"""
       return (
           sum(self.embedding_dimension							)
           + self.num_dynamic_real_features
           + self.num_time_features
           + self.num_static_real_features
           + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
       )

