




'''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 						snake_case_       (UpperCamelCase			:    Optional[int]					,		UpperCamelCase			:    Tuple ):





							'''simple docstring'''


							_a      	=							checkpoint

							_a      	=							{}

							_a      	=							vae_state_dict['''encoder.conv_in.weight''']
							_a      	=							vae_state_dict['''encoder.conv_in.bias''']
							_a      	=							vae_state_dict['''encoder.conv_out.weight''']
							_a      	=							vae_state_dict['''encoder.conv_out.bias''']
							_a      	=							vae_state_dict['''encoder.norm_out.weight''']
							_a      	=							vae_state_dict['''encoder.norm_out.bias''']

							_a      	=							vae_state_dict['''decoder.conv_in.weight''']
							_a      	=							vae_state_dict['''decoder.conv_in.bias''']
							_a      	=							vae_state_dict['''decoder.conv_out.weight''']
							_a      	=							vae_state_dict['''decoder.conv_out.bias''']
							_a      	=							vae_state_dict['''decoder.norm_out.weight''']
							_a      	=							vae_state_dict['''decoder.norm_out.bias''']

							_a      	=							vae_state_dict['''quant_conv.weight''']
							_a      	=							vae_state_dict['''quant_conv.bias''']
							_a      	=							vae_state_dict['''post_quant_conv.weight''']
							_a      	=							vae_state_dict['''post_quant_conv.bias''']

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

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

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

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

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

														_a      	=							renew_vae_resnet_paths(UpperCamelCase )
														_a      	=							{'''old''': f'up.{block_id}.block', '''new''': f'up_blocks.{i}.resnets'}
														assign_to_checkpoint(UpperCamelCase					,		UpperCamelCase					,		UpperCamelCase					,		additional_replacements=[meta_path]					,		config=UpperCamelCase )

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

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

							_a      	=							[key for key in vae_state_dict if '''decoder.mid.attn''' in key]
							_a      	=							renew_vae_attention_paths(UpperCamelCase )
							_a      	=							{'''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 						snake_case_       (UpperCamelCase			:    str					,		UpperCamelCase			:    str					,		):





							'''simple docstring'''


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

							_a      	=							OmegaConf.load(UpperCamelCase )
							_a      	=							512
							_a      	=							'''cuda''' if torch.cuda.is_available() else '''cpu'''
							if checkpoint_path.endswith('''safetensors''' ):
														from safetensors import safe_open

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

							# Convert the VAE model.
							_a      	=							create_vae_diffusers_config(UpperCamelCase					,		image_size=UpperCamelCase )
							_a      	=							custom_convert_ldm_vae_checkpoint(UpperCamelCase					,		UpperCamelCase )

							_a      	=							AutoencoderKL(**UpperCamelCase )
							vae.load_state_dict(UpperCamelCase )
							vae.save_pretrained(UpperCamelCase )


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

				_snake_case : Tuple  				=						parser.parse_args()

				vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)







import argparse

import torch

from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel
from transformers.utils import logging


logging.set_verbosity_info()

def lowercase    (  SCREAMING_SNAKE_CASE       ,    SCREAMING_SNAKE_CASE       ,    SCREAMING_SNAKE_CASE       ,    SCREAMING_SNAKE_CASE )			->							Union[str, Any]:


			'''simple docstring'''







			SCREAMING_SNAKE_CASE_								=						FunnelConfig.from_json_file(SCREAMING_SNAKE_CASE )
			print(F'Building PyTorch model from configuration: {config}' )
			SCREAMING_SNAKE_CASE_								=						FunnelBaseModel(SCREAMING_SNAKE_CASE ) if base_model else FunnelModel(SCREAMING_SNAKE_CASE )

			# Load weights from tf checkpoint
			load_tf_weights_in_funnel(SCREAMING_SNAKE_CASE       ,    SCREAMING_SNAKE_CASE       ,    SCREAMING_SNAKE_CASE )

			# Save pytorch-model
			print(F'Save PyTorch model to {pytorch_dump_path}' )
			torch.save(model.state_dict()       ,    SCREAMING_SNAKE_CASE )


if __name__ == "__main__":
				SCREAMING_SNAKE_CASE__     :     Union[str, Any]		    =       argparse.ArgumentParser()
				# Required parameters
				parser.add_argument(
				    "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
				)
				parser.add_argument(
				    "--config_file",
				    default=None,
				    type=str,
				    required=True,
				    help="The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.",
				)
				parser.add_argument(
				    "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
				)
				parser.add_argument(
				    "--base_model", action="store_true", help="Whether you want just the base model (no decoder) or not."
				)
				SCREAMING_SNAKE_CASE__     :     List[Any]		    =       parser.parse_args()
				convert_tf_checkpoint_to_pytorch(
				    args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path, args.base_model
				)
