






"""simple docstring"""






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 					_A			(__a    ,				__a							) ->       int:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_      :  int    						=		checkpoint

    SCREAMING_SNAKE_CASE_      :  str    						=		{}

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

    SCREAMING_SNAKE_CASE_      :  int    						=		vae_state_dict['''decoder.conv_in.weight''']
    SCREAMING_SNAKE_CASE_      :  Any    						=		vae_state_dict['''decoder.conv_in.bias''']
    SCREAMING_SNAKE_CASE_      :  Tuple    						=		vae_state_dict['''decoder.conv_out.weight''']
    SCREAMING_SNAKE_CASE_      :  Any    						=		vae_state_dict['''decoder.conv_out.bias''']
    SCREAMING_SNAKE_CASE_      :  List[Any]    						=		vae_state_dict['''decoder.norm_out.weight''']
    SCREAMING_SNAKE_CASE_      :  int    						=		vae_state_dict['''decoder.norm_out.bias''']

    SCREAMING_SNAKE_CASE_      :  str    						=		vae_state_dict['''quant_conv.weight''']
    SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		vae_state_dict['''quant_conv.bias''']
    SCREAMING_SNAKE_CASE_      :  int    						=		vae_state_dict['''post_quant_conv.weight''']
    SCREAMING_SNAKE_CASE_      :  int    						=		vae_state_dict['''post_quant_conv.bias''']

    # Retrieves the keys for the encoder down blocks only
    SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		len({'''.'''.join(layer.split('''.'''							)[:3]							) for layer in vae_state_dict if '''encoder.down''' in layer}							)
    SCREAMING_SNAKE_CASE_      :  Tuple    						=		{
        layer_id: [key for key in vae_state_dict if f'down.{layer_id}' in key] for layer_id in range(__a							)
    }

    # Retrieves the keys for the decoder up blocks only
    SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		len({'''.'''.join(layer.split('''.'''							)[:3]							) for layer in vae_state_dict if '''decoder.up''' in layer}							)
    SCREAMING_SNAKE_CASE_      :  Tuple    						=		{
        layer_id: [key for key in vae_state_dict if f'up.{layer_id}' in key] for layer_id in range(__a							)
    }

    for i in range(__a							):
        SCREAMING_SNAKE_CASE_      :  Union[str, 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:
            SCREAMING_SNAKE_CASE_      :  List[str]    						=		vae_state_dict.pop(
                f'encoder.down.{i}.downsample.conv.weight'							)
            SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		vae_state_dict.pop(
                f'encoder.down.{i}.downsample.conv.bias'							)

        SCREAMING_SNAKE_CASE_      :  List[Any]    						=		renew_vae_resnet_paths(__a							)
        SCREAMING_SNAKE_CASE_      :  List[Any]    						=		{'''old''': f'down.{i}.block', '''new''': f'down_blocks.{i}.resnets'}
        assign_to_checkpoint(__a    ,				__a    ,				__a    ,				additional_replacements=[meta_path]    ,				config=__a							)

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

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

    SCREAMING_SNAKE_CASE_      :  Dict    						=		[key for key in vae_state_dict if '''encoder.mid.attn''' in key]
    SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		renew_vae_attention_paths(__a							)
    SCREAMING_SNAKE_CASE_      :  Tuple    						=		{'''old''': '''mid.attn_1''', '''new''': '''mid_block.attentions.0'''}
    assign_to_checkpoint(__a    ,				__a    ,				__a    ,				additional_replacements=[meta_path]    ,				config=__a							)
    conv_attn_to_linear(__a							)

    for i in range(__a							):
        SCREAMING_SNAKE_CASE_      :  List[str]    						=		num_up_blocks - 1 - i
        SCREAMING_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:
            SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		vae_state_dict[
                f'decoder.up.{block_id}.upsample.conv.weight'
            ]
            SCREAMING_SNAKE_CASE_      :  str    						=		vae_state_dict[
                f'decoder.up.{block_id}.upsample.conv.bias'
            ]

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

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

        SCREAMING_SNAKE_CASE_      :  int    						=		renew_vae_resnet_paths(__a							)
        SCREAMING_SNAKE_CASE_      :  Tuple    						=		{'''old''': f'mid.block_{i}', '''new''': f'mid_block.resnets.{i - 1}'}
        assign_to_checkpoint(__a    ,				__a    ,				__a    ,				additional_replacements=[meta_path]    ,				config=__a							)

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



def 					_A			(__a    ,				__a    ,				) ->       Tuple:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		requests.get(
        ''' https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml'''							)
    SCREAMING_SNAKE_CASE_      :  Dict    						=		io.BytesIO(r.content							)

    SCREAMING_SNAKE_CASE_      :  Any    						=		OmegaConf.load(__a							)
    SCREAMING_SNAKE_CASE_      :  int    						=		5_12
    SCREAMING_SNAKE_CASE_      :  str    						=		'''cuda''' if torch.cuda.is_available() else '''cpu'''
    if checkpoint_path.endswith('''safetensors'''							):
        from safetensors import safe_open

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

    # Convert the VAE model.
    SCREAMING_SNAKE_CASE_      :  Any    						=		create_vae_diffusers_config(__a    ,				image_size=__a							)
    SCREAMING_SNAKE_CASE_      :  int    						=		custom_convert_ldm_vae_checkpoint(__a    ,				__a							)

    SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		AutoencoderKL(**__a							)
    vae.load_state_dict(__a							)
    vae.save_pretrained(__a							)


if __name__ == "__main__":
  UpperCAmelCase_   : int   			= 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_   : Any   			= parser.parse_args()

  vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)










"""simple docstring"""






def 					_A			(__a = 50							) ->       int:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_      :  Tuple    						=		[[0] * 3 for _ in range(length + 1							)]

    for row_length in range(length + 1							):
        for tile_length in range(2    ,				5							):
            for tile_start in range(row_length - tile_length + 1							):
                different_colour_ways_number[row_length][tile_length - 2] += (
                    different_colour_ways_number[row_length - tile_start - tile_length][
                        tile_length - 2
                    ]
                    + 1
                )

    return sum(different_colour_ways_number[length]							)


if __name__ == "__main__":
  print(f'''{solution() = }''')


