






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 				snake_case  (     lowerCamelCase				,  lowerCamelCase					):




	'''simple docstring'''







	__lowercase             =  checkpoint

	__lowercase             =  {}

	__lowercase             =  vae_state_dict["""encoder.conv_in.weight"""]
	__lowercase             =  vae_state_dict["""encoder.conv_in.bias"""]
	__lowercase             =  vae_state_dict["""encoder.conv_out.weight"""]
	__lowercase             =  vae_state_dict["""encoder.conv_out.bias"""]
	__lowercase             =  vae_state_dict["""encoder.norm_out.weight"""]
	__lowercase             =  vae_state_dict["""encoder.norm_out.bias"""]

	__lowercase             =  vae_state_dict["""decoder.conv_in.weight"""]
	__lowercase             =  vae_state_dict["""decoder.conv_in.bias"""]
	__lowercase             =  vae_state_dict["""decoder.conv_out.weight"""]
	__lowercase             =  vae_state_dict["""decoder.conv_out.bias"""]
	__lowercase             =  vae_state_dict["""decoder.norm_out.weight"""]
	__lowercase             =  vae_state_dict["""decoder.norm_out.bias"""]

	__lowercase             =  vae_state_dict["""quant_conv.weight"""]
	__lowercase             =  vae_state_dict["""quant_conv.bias"""]
	__lowercase             =  vae_state_dict["""post_quant_conv.weight"""]
	__lowercase             =  vae_state_dict["""post_quant_conv.bias"""]

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

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

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

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

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

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

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

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

	__lowercase             =  [key for key in vae_state_dict if """decoder.mid.attn""" in key]
	__lowercase             =  renew_vae_attention_paths(lowerCamelCase					)
	__lowercase             =  {"""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 				snake_case  (     lowerCamelCase				,  lowerCamelCase				,  ):




	'''simple docstring'''







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

	__lowercase             =  OmegaConf.load(lowerCamelCase					)
	__lowercase             =  512
	__lowercase             =  """cuda""" if torch.cuda.is_available() else """cpu"""
	if checkpoint_path.endswith("""safetensors"""					):
		from safetensors import safe_open

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

	# Convert the VAE model.
	__lowercase             =  create_vae_diffusers_config(lowerCamelCase				,  image_size=lowerCamelCase					)
	__lowercase             =  custom_convert_ldm_vae_checkpoint(lowerCamelCase				,  lowerCamelCase					)

	__lowercase             =  AutoencoderKL(**lowerCamelCase					)
	vae.load_state_dict(lowerCamelCase					)
	vae.save_pretrained(lowerCamelCase					)


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

						__UpperCamelCase      :      Tuple     						=						parser.parse_args()

						vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)










from __future__ import annotations





def 				snake_case  (     lowerCamelCase					):




	'''simple docstring'''







	if not nums:
		return 0
	__lowercase             =  nums[0]
	__lowercase             =  0
	for num in nums[1:]:
		__lowercase       ,						__lowercase             =  (
		    max_excluding + num,
		    max(lowerCamelCase				,  lowerCamelCase					),
		)
	return max(lowerCamelCase				,  lowerCamelCase					)


if __name__ == "__main__":
						import doctest

						doctest.testmod()

