


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							,			__lowerCamelCase			):
							__snake_case	:    int											=     checkpoint

							__snake_case	:    int											=     {}

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

							__snake_case	:    int											=     vae_state_dict["decoder.conv_in.weight"]
							__snake_case	:    Any											=     vae_state_dict["decoder.conv_in.bias"]
							__snake_case	:    Dict											=     vae_state_dict["decoder.conv_out.weight"]
							__snake_case	:    int											=     vae_state_dict["decoder.conv_out.bias"]
							__snake_case	:    int											=     vae_state_dict["decoder.norm_out.weight"]
							__snake_case	:    Optional[Any]											=     vae_state_dict["decoder.norm_out.bias"]

							__snake_case	:    Any											=     vae_state_dict["quant_conv.weight"]
							__snake_case	:    Dict											=     vae_state_dict["quant_conv.bias"]
							__snake_case	:    Any											=     vae_state_dict["post_quant_conv.weight"]
							__snake_case	:    Union[str, Any]											=     vae_state_dict["post_quant_conv.bias"]

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

														__snake_case	:    str											=     renew_vae_resnet_paths(__lowerCamelCase			)
														__snake_case	:    Tuple											=     {"old": F'down.{i}.block', "new": F'down_blocks.{i}.resnets'}
														assign_to_checkpoint(__lowerCamelCase							,			__lowerCamelCase							,			__lowerCamelCase							,			additional_replacements=[meta_path]							,			config=__lowerCamelCase			)

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

														__snake_case	:    List[Any]											=     renew_vae_resnet_paths(__lowerCamelCase			)
														__snake_case	:    Union[str, Any]											=     {"old": F'mid.block_{i}', "new": F'mid_block.resnets.{i - 1}'}
														assign_to_checkpoint(__lowerCamelCase							,			__lowerCamelCase							,			__lowerCamelCase							,			additional_replacements=[meta_path]							,			config=__lowerCamelCase			)

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

														__snake_case	:    Union[str, Any]											=     renew_vae_resnet_paths(__lowerCamelCase			)
														__snake_case	:    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			)

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

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

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

							__snake_case	:    Any											=     OmegaConf.load(__lowerCamelCase			)
							__snake_case	:    Tuple											=     5_1_2
							__snake_case	:    Any											=     "cuda" if torch.cuda.is_available() else "cpu"
							if checkpoint_path.endswith("safetensors"			):
														from safetensors import safe_open

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

							# Convert the VAE model.
							__snake_case	:    Optional[Any]											=     create_vae_diffusers_config(__lowerCamelCase							,			image_size=__lowerCamelCase			)
							__snake_case	:    Dict											=     custom_convert_ldm_vae_checkpoint(__lowerCamelCase							,			__lowerCamelCase			)

							__snake_case	:    str											=     AutoencoderKL(**__lowerCamelCase			)
							vae.load_state_dict(__lowerCamelCase			)
							vae.save_pretrained(__lowerCamelCase			)


if __name__ == "__main__":
			_snake_case  :	List[str]			      =       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  :	Optional[Any]			      =       parser.parse_args()

			vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)





import os
import socket
from contextlib import contextmanager

import torch

from ..commands.config.default import write_basic_config  # noqa: F401
from ..state import PartialState
from .dataclasses import DistributedType
from .imports import is_deepspeed_available, is_tpu_available
from .transformer_engine import convert_model
from .versions import is_torch_version


if is_deepspeed_available():
			from deepspeed import DeepSpeedEngine

if is_tpu_available(check_device=False):
			import torch_xla.core.xla_model as xm







def        lowerCAmelCase_  (      __lowerCamelCase			):
							if is_torch_version("<"							,			"2.0.0"			) or not hasattr(__lowerCamelCase							,			"_dynamo"			):
														return False
							return isinstance(__lowerCamelCase							,			torch._dynamo.eval_frame.OptimizedModule			)







def        lowerCAmelCase_  (      __lowerCamelCase							,			__lowerCamelCase = True			):
							__snake_case	:    Optional[Any]											=     (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)

							__snake_case	:    Tuple											=     is_compiled_module(__lowerCamelCase			)
							if is_compiled:
														__snake_case	:    Tuple											=     model
														__snake_case	:    List[str]											=     model._orig_mod

							if is_deepspeed_available():
														options += (DeepSpeedEngine,)

							while isinstance(__lowerCamelCase							,			__lowerCamelCase			):
														__snake_case	:    List[Any]											=     model.module

							if not keep_fpaa_wrapper:
														__snake_case	:    Tuple											=     getattr(__lowerCamelCase							,			"forward"			)
														__snake_case	:    int											=     model.__dict__.pop("_original_forward"							,			__lowerCamelCase			)
														if original_forward is not None:
																					while hasattr(__lowerCamelCase							,			"__wrapped__"			):
																												__snake_case	:    str											=     forward.__wrapped__
																												if forward == original_forward:
																																			break
																					__snake_case	:    Dict											=     forward
														if getattr(__lowerCamelCase							,			"_converted_to_transformer_engine"							,			__lowerCamelCase			):
																					convert_model(__lowerCamelCase							,			to_transformer_engine=__lowerCamelCase			)

							if is_compiled:
														__snake_case	:    Tuple											=     model
														__snake_case	:    str											=     compiled_model

							return model







def        lowerCAmelCase_  (      ):
							PartialState().wait_for_everyone()







def        lowerCAmelCase_  (      __lowerCamelCase							,			__lowerCamelCase			):
							if PartialState().distributed_type == DistributedType.TPU:
														xm.save(__lowerCamelCase							,			__lowerCamelCase			)
							elif PartialState().local_process_index == 0:
														torch.save(__lowerCamelCase							,			__lowerCamelCase			)







@contextmanager
def        lowerCAmelCase_  (      **__lowerCamelCase			):
							for key, value in kwargs.items():
														__snake_case	:    Union[str, Any]											=     str(__lowerCamelCase			)

							yield

							for key in kwargs:
														if key.upper() in os.environ:
																					del os.environ[key.upper()]







def        lowerCAmelCase_  (      __lowerCamelCase			):
							if not hasattr(__lowerCamelCase							,			"__qualname__"			) and not hasattr(__lowerCamelCase							,			"__name__"			):
														__snake_case	:    Dict											=     getattr(__lowerCamelCase							,			"__class__"							,			__lowerCamelCase			)
							if hasattr(__lowerCamelCase							,			"__qualname__"			):
														return obj.__qualname__
							if hasattr(__lowerCamelCase							,			"__name__"			):
														return obj.__name__
							return str(__lowerCamelCase			)







def        lowerCAmelCase_  (      __lowerCamelCase							,			__lowerCamelCase			):
							for key, value in source.items():
														if isinstance(__lowerCamelCase							,			__lowerCamelCase			):
																					__snake_case	:    Tuple											=     destination.setdefault(__lowerCamelCase							,			{}			)
																					merge_dicts(__lowerCamelCase							,			__lowerCamelCase			)
														else:
																					__snake_case	:    Union[str, Any]											=     value

							return destination







def        lowerCAmelCase_  (      __lowerCamelCase = None			):
							if port is None:
														__snake_case	:    List[str]											=     2_9_5_0_0
							with socket.socket(socket.AF_INET							,			socket.SOCK_STREAM			) as s:
														return s.connect_ex(("localhost", port)			) == 0

