



'''simple docstring'''






import logging
import os

from .state import PartialState

class 				SCREAMING_SNAKE_CASE(							logging.LoggerAdapter			):







	"""simple docstring"""






	@staticmethod
	def      A	(						__snake_case			:     Tuple		)			->		Optional[int]:
								UpperCAmelCase :       List[str] 							=		PartialState()
								return not main_process_only or (main_process_only and state.is_main_process)







	def      A	(						self			:     List[Any]		,			__snake_case			:     Dict		,			__snake_case			:     int		,			*__snake_case			:     List[str]		,			**__snake_case			:     Optional[Any]		)			->		Union[str, Any]:
								if PartialState._shared_state == {}:
															raise RuntimeError(
															    '''You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.'''		)
								UpperCAmelCase :       Dict 							=		kwargs.pop('''main_process_only'''		,			__snake_case		)
								UpperCAmelCase :       Dict 							=		kwargs.pop('''in_order'''		,			__snake_case		)

								if self.isEnabledFor(__snake_case		):
															if self._should_log(__snake_case		):
																						UpperCAmelCase							,		UpperCAmelCase :       Any 							=		self.process(__snake_case		,			__snake_case		)
																						self.logger.log(__snake_case		,			__snake_case		,			*__snake_case		,			**__snake_case		)

															elif in_order:
																						UpperCAmelCase :       Tuple 							=		PartialState()
																						for i in range(state.num_processes		):
																													if i == state.process_index:
																																				UpperCAmelCase							,		UpperCAmelCase :       List[Any] 							=		self.process(__snake_case		,			__snake_case		)
																																				self.logger.log(__snake_case		,			__snake_case		,			*__snake_case		,			**__snake_case		)
																													state.wait_for_everyone()


def  snake_case_     (					_lowerCAmelCase  :						str   ,      _lowerCAmelCase  :						str = None  )      ->   List[Any]:
							if log_level is None:
														UpperCAmelCase :       Union[str, Any] 							=		os.environ.get('''ACCELERATE_LOG_LEVEL'''   ,      _lowerCAmelCase  )
							UpperCAmelCase :       Dict 							=		logging.getLogger(_lowerCAmelCase  )
							if log_level is not None:
														logger.setLevel(log_level.upper()  )
														logger.root.setLevel(log_level.upper()  )
							return MultiProcessAdapter(_lowerCAmelCase   ,      {}  )













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__      (    __lowerCamelCase			:     Dict  ,		__lowerCamelCase			:     int		):
  __UpperCAmelCase							:	List[Any]           =  checkpoint

  __UpperCAmelCase							:	Tuple           =  {}

  __UpperCAmelCase							:	Dict           =  vae_state_dict["""encoder.conv_in.weight"""]
  __UpperCAmelCase							:	Optional[Any]           =  vae_state_dict["""encoder.conv_in.bias"""]
  __UpperCAmelCase							:	Dict           =  vae_state_dict["""encoder.conv_out.weight"""]
  __UpperCAmelCase							:	Union[str, Any]           =  vae_state_dict["""encoder.conv_out.bias"""]
  __UpperCAmelCase							:	List[Any]           =  vae_state_dict["""encoder.norm_out.weight"""]
  __UpperCAmelCase							:	Tuple           =  vae_state_dict["""encoder.norm_out.bias"""]

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

  __UpperCAmelCase							:	Optional[int]           =  vae_state_dict["""quant_conv.weight"""]
  __UpperCAmelCase							:	int           =  vae_state_dict["""quant_conv.bias"""]
  __UpperCAmelCase							:	Union[str, Any]           =  vae_state_dict["""post_quant_conv.weight"""]
  __UpperCAmelCase							:	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							:	Optional[Any]           =  {
      layer_id: [key for key in vae_state_dict if f"""down.{layer_id}""" in key] for layer_id in range(__lowerCamelCase		)
  }

  # Retrieves the keys for the decoder up blocks only
  __UpperCAmelCase							:	Dict           =  len({""".""".join(layer.split("""."""		)[:3]		) for layer in vae_state_dict if """decoder.up""" in layer}		)
  __UpperCAmelCase							:	Optional[int]           =  {
      layer_id: [key for key in vae_state_dict if f"""up.{layer_id}""" in key] for layer_id in range(__lowerCamelCase		)
  }

  for i in range(__lowerCamelCase		):
    __UpperCAmelCase							:	List[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:
      __UpperCAmelCase							:	Optional[Any]           =  vae_state_dict.pop(
          f"""encoder.down.{i}.downsample.conv.weight"""		)
      __UpperCAmelCase							:	int           =  vae_state_dict.pop(
          f"""encoder.down.{i}.downsample.conv.bias"""		)

    __UpperCAmelCase							:	Optional[int]           =  renew_vae_resnet_paths(__lowerCamelCase		)
    __UpperCAmelCase							:	Optional[Any]           =  {"""old""": f"""down.{i}.block""", """new""": f"""down_blocks.{i}.resnets"""}
    assign_to_checkpoint(__lowerCamelCase  ,		__lowerCamelCase  ,		__lowerCamelCase  ,		additional_replacements=[meta_path]  ,		config=__lowerCamelCase		)

  __UpperCAmelCase							:	Tuple           =  [key for key in vae_state_dict if """encoder.mid.block""" in key]
  __UpperCAmelCase							:	Optional[Any]           =  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(__lowerCamelCase		)
    __UpperCAmelCase							:	Tuple           =  {"""old""": f"""mid.block_{i}""", """new""": f"""mid_block.resnets.{i - 1}"""}
    assign_to_checkpoint(__lowerCamelCase  ,		__lowerCamelCase  ,		__lowerCamelCase  ,		additional_replacements=[meta_path]  ,		config=__lowerCamelCase		)

  __UpperCAmelCase							:	List[Any]           =  [key for key in vae_state_dict if """encoder.mid.attn""" in key]
  __UpperCAmelCase							:	str           =  renew_vae_attention_paths(__lowerCamelCase		)
  __UpperCAmelCase							:	List[str]           =  {"""old""": """mid.attn_1""", """new""": """mid_block.attentions.0"""}
  assign_to_checkpoint(__lowerCamelCase  ,		__lowerCamelCase  ,		__lowerCamelCase  ,		additional_replacements=[meta_path]  ,		config=__lowerCamelCase		)
  conv_attn_to_linear(__lowerCamelCase		)

  for i in range(__lowerCamelCase		):
    __UpperCAmelCase							:	Optional[Any]           =  num_up_blocks - 1 - i
    __UpperCAmelCase							:	Union[str, Any]           =  [
        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							:	int           =  vae_state_dict[
          f"""decoder.up.{block_id}.upsample.conv.weight"""
      ]
      __UpperCAmelCase							:	Dict           =  vae_state_dict[
          f"""decoder.up.{block_id}.upsample.conv.bias"""
      ]

    __UpperCAmelCase							:	Dict           =  renew_vae_resnet_paths(__lowerCamelCase		)
    __UpperCAmelCase							:	Optional[Any]           =  {"""old""": f"""up.{block_id}.block""", """new""": f"""up_blocks.{i}.resnets"""}
    assign_to_checkpoint(__lowerCamelCase  ,		__lowerCamelCase  ,		__lowerCamelCase  ,		additional_replacements=[meta_path]  ,		config=__lowerCamelCase		)

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

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

  __UpperCAmelCase							:	Dict           =  [key for key in vae_state_dict if """decoder.mid.attn""" in key]
  __UpperCAmelCase							:	List[Any]           =  renew_vae_attention_paths(__lowerCamelCase		)
  __UpperCAmelCase							:	List[str]           =  {"""old""": """mid.attn_1""", """new""": """mid_block.attentions.0"""}
  assign_to_checkpoint(__lowerCamelCase  ,		__lowerCamelCase  ,		__lowerCamelCase  ,		additional_replacements=[meta_path]  ,		config=__lowerCamelCase		)
  conv_attn_to_linear(__lowerCamelCase		)
  return new_checkpoint






def 				lowerCamelCase__      (    __lowerCamelCase			:     str  ,		__lowerCamelCase			:     str  ,		):
  # Only support V1
  __UpperCAmelCase							:	Optional[int]           =  requests.get(
      """ https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml"""		)
  __UpperCAmelCase							:	Optional[int]           =  io.BytesIO(r.content		)

  __UpperCAmelCase							:	Dict           =  OmegaConf.load(__lowerCamelCase		)
  __UpperCAmelCase							:	str           =  512
  __UpperCAmelCase							:	Any           =  """cuda""" if torch.cuda.is_available() else """cpu"""
  if checkpoint_path.endswith("""safetensors"""		):
    from safetensors import safe_open

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

  # Convert the VAE model.
  __UpperCAmelCase							:	Optional[int]           =  create_vae_diffusers_config(__lowerCamelCase  ,		image_size=__lowerCamelCase		)
  __UpperCAmelCase							:	Union[str, Any]           =  custom_convert_ldm_vae_checkpoint(__lowerCamelCase  ,		__lowerCamelCase		)

  __UpperCAmelCase							:	Optional[int]           =  AutoencoderKL(**__lowerCamelCase		)
  vae.load_state_dict(__lowerCamelCase		)
  vae.save_pretrained(__lowerCamelCase		)


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

       a		:       Optional[int]			     = parser.parse_args()

       vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)


