






'''simple docstring'''





import argparse
from collections import OrderedDict
from pathlib import Path

import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from torchvision.transforms import functional as F

from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection
from transformers.utils import logging


logging.set_verbosity_info()
A        =			logging.get_logger(__name__)

# here we list all keys to be renamed (original name on the left, our name on the right)
A        =			[]
for i in range(6):
				# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
				rename_keys.append(
				    (f"""transformer.encoder.layers.{i}.self_attn.out_proj.weight""", f"""encoder.layers.{i}.self_attn.out_proj.weight""")
				)
				rename_keys.append(
				    (f"""transformer.encoder.layers.{i}.self_attn.out_proj.bias""", f"""encoder.layers.{i}.self_attn.out_proj.bias""")
				)
				rename_keys.append((f"""transformer.encoder.layers.{i}.linear1.weight""", f"""encoder.layers.{i}.fc1.weight"""))
				rename_keys.append((f"""transformer.encoder.layers.{i}.linear1.bias""", f"""encoder.layers.{i}.fc1.bias"""))
				rename_keys.append((f"""transformer.encoder.layers.{i}.linear2.weight""", f"""encoder.layers.{i}.fc2.weight"""))
				rename_keys.append((f"""transformer.encoder.layers.{i}.linear2.bias""", f"""encoder.layers.{i}.fc2.bias"""))
				rename_keys.append(
				    (f"""transformer.encoder.layers.{i}.norm1.weight""", f"""encoder.layers.{i}.self_attn_layer_norm.weight""")
				)
				rename_keys.append((f"""transformer.encoder.layers.{i}.norm1.bias""", f"""encoder.layers.{i}.self_attn_layer_norm.bias"""))
				rename_keys.append((f"""transformer.encoder.layers.{i}.norm2.weight""", f"""encoder.layers.{i}.final_layer_norm.weight"""))
				rename_keys.append((f"""transformer.encoder.layers.{i}.norm2.bias""", f"""encoder.layers.{i}.final_layer_norm.bias"""))
				# decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms
				rename_keys.append(
				    (f"""transformer.decoder.layers.{i}.self_attn.out_proj.weight""", f"""decoder.layers.{i}.self_attn.out_proj.weight""")
				)
				rename_keys.append(
				    (f"""transformer.decoder.layers.{i}.self_attn.out_proj.bias""", f"""decoder.layers.{i}.self_attn.out_proj.bias""")
				)
				rename_keys.append(
				    (
				        f"""transformer.decoder.layers.{i}.multihead_attn.out_proj.weight""",
				        f"""decoder.layers.{i}.encoder_attn.out_proj.weight""",
				    )
				)
				rename_keys.append(
				    (
				        f"""transformer.decoder.layers.{i}.multihead_attn.out_proj.bias""",
				        f"""decoder.layers.{i}.encoder_attn.out_proj.bias""",
				    )
				)
				rename_keys.append((f"""transformer.decoder.layers.{i}.linear1.weight""", f"""decoder.layers.{i}.fc1.weight"""))
				rename_keys.append((f"""transformer.decoder.layers.{i}.linear1.bias""", f"""decoder.layers.{i}.fc1.bias"""))
				rename_keys.append((f"""transformer.decoder.layers.{i}.linear2.weight""", f"""decoder.layers.{i}.fc2.weight"""))
				rename_keys.append((f"""transformer.decoder.layers.{i}.linear2.bias""", f"""decoder.layers.{i}.fc2.bias"""))
				rename_keys.append(
				    (f"""transformer.decoder.layers.{i}.norm1.weight""", f"""decoder.layers.{i}.self_attn_layer_norm.weight""")
				)
				rename_keys.append((f"""transformer.decoder.layers.{i}.norm1.bias""", f"""decoder.layers.{i}.self_attn_layer_norm.bias"""))
				rename_keys.append(
				    (f"""transformer.decoder.layers.{i}.norm2.weight""", f"""decoder.layers.{i}.encoder_attn_layer_norm.weight""")
				)
				rename_keys.append(
				    (f"""transformer.decoder.layers.{i}.norm2.bias""", f"""decoder.layers.{i}.encoder_attn_layer_norm.bias""")
				)
				rename_keys.append((f"""transformer.decoder.layers.{i}.norm3.weight""", f"""decoder.layers.{i}.final_layer_norm.weight"""))
				rename_keys.append((f"""transformer.decoder.layers.{i}.norm3.bias""", f"""decoder.layers.{i}.final_layer_norm.bias"""))

# convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads
rename_keys.extend(
    [
        ('input_proj.weight', 'input_projection.weight'),
        ('input_proj.bias', 'input_projection.bias'),
        ('query_embed.weight', 'query_position_embeddings.weight'),
        ('transformer.encoder.norm.weight', 'encoder.layernorm.weight'),
        ('transformer.encoder.norm.bias', 'encoder.layernorm.bias'),
        ('transformer.decoder.norm.weight', 'decoder.layernorm.weight'),
        ('transformer.decoder.norm.bias', 'decoder.layernorm.bias'),
        ('class_embed.weight', 'class_labels_classifier.weight'),
        ('class_embed.bias', 'class_labels_classifier.bias'),
        ('bbox_embed.layers.0.weight', 'bbox_predictor.layers.0.weight'),
        ('bbox_embed.layers.0.bias', 'bbox_predictor.layers.0.bias'),
        ('bbox_embed.layers.1.weight', 'bbox_predictor.layers.1.weight'),
        ('bbox_embed.layers.1.bias', 'bbox_predictor.layers.1.bias'),
        ('bbox_embed.layers.2.weight', 'bbox_predictor.layers.2.weight'),
        ('bbox_embed.layers.2.bias', 'bbox_predictor.layers.2.bias'),
    ]
)



def 					_lowerCamelCase(			lowerCAmelCase__				:		int    ,    lowerCAmelCase__				:		Tuple    ,    lowerCAmelCase__				:		List[str]      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	Optional[int]													=   state_dict.pop(lowerCAmelCase__      )
				SCREAMING_SNAKE_CASE_   :	Optional[int]													=   val



def 					_lowerCamelCase(			lowerCAmelCase__				:		List[str]      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	List[str]													=   OrderedDict()
				for key, value in state_dict.items():
								if "backbone.0.body" in key:
												SCREAMING_SNAKE_CASE_   :	Dict													=   key.replace('backbone.0.body'    ,    'backbone.conv_encoder.model'      )
												SCREAMING_SNAKE_CASE_   :	List[str]													=   value
								else:
												SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   value

				return new_state_dict



def 					_lowerCamelCase(			lowerCAmelCase__				:		str      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   ''

				# first: transformer encoder
				for i in range(6      ):
								# read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias)
								SCREAMING_SNAKE_CASE_   :	Dict													=   state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight'''      )
								SCREAMING_SNAKE_CASE_   :	Optional[int]													=   state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias'''      )
								# next, add query, keys and values (in that order) to the state dict
								SCREAMING_SNAKE_CASE_   :	List[str]													=   in_proj_weight[:256, :]
								SCREAMING_SNAKE_CASE_   :	Dict													=   in_proj_bias[:256]
								SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   in_proj_weight[256:512, :]
								SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   in_proj_bias[256:512]
								SCREAMING_SNAKE_CASE_   :	Any													=   in_proj_weight[-256:, :]
								SCREAMING_SNAKE_CASE_   :	Any													=   in_proj_bias[-256:]
				# next: transformer decoder (which is a bit more complex because it also includes cross-attention)
				for i in range(6      ):
								# read in weights + bias of input projection layer of self-attention
								SCREAMING_SNAKE_CASE_   :	List[str]													=   state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight'''      )
								SCREAMING_SNAKE_CASE_   :	int													=   state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias'''      )
								# next, add query, keys and values (in that order) to the state dict
								SCREAMING_SNAKE_CASE_   :	Dict													=   in_proj_weight[:256, :]
								SCREAMING_SNAKE_CASE_   :	str													=   in_proj_bias[:256]
								SCREAMING_SNAKE_CASE_   :	int													=   in_proj_weight[256:512, :]
								SCREAMING_SNAKE_CASE_   :	int													=   in_proj_bias[256:512]
								SCREAMING_SNAKE_CASE_   :	Dict													=   in_proj_weight[-256:, :]
								SCREAMING_SNAKE_CASE_   :	str													=   in_proj_bias[-256:]
								# read in weights + bias of input projection layer of cross-attention
								SCREAMING_SNAKE_CASE_   :	Optional[int]													=   state_dict.pop(
								    F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight'''      )
								SCREAMING_SNAKE_CASE_   :	Any													=   state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias'''      )
								# next, add query, keys and values (in that order) of cross-attention to the state dict
								SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   in_proj_weight_cross_attn[:256, :]
								SCREAMING_SNAKE_CASE_   :	str													=   in_proj_bias_cross_attn[:256]
								SCREAMING_SNAKE_CASE_   :	Any													=   in_proj_weight_cross_attn[256:512, :]
								SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   in_proj_bias_cross_attn[256:512]
								SCREAMING_SNAKE_CASE_   :	Tuple													=   in_proj_weight_cross_attn[-256:, :]
								SCREAMING_SNAKE_CASE_   :	List[Any]													=   in_proj_bias_cross_attn[-256:]



def 					_lowerCamelCase(			lowerCAmelCase__				:		List[str]    ,    lowerCAmelCase__				:		Optional[int]      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	Any													=   image.size
				SCREAMING_SNAKE_CASE_   :	Tuple													=   max(lowerCAmelCase__    ,    lowerCAmelCase__      )
				SCREAMING_SNAKE_CASE_   :	int													=   800 if 'detection' in checkpoint_url else 1000
				SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   target_max_size / current_max_size
				SCREAMING_SNAKE_CASE_   :	Tuple													=   image.resize((int(round(scale * width      )      ), int(round(scale * height      )      ))      )

				return resized_image



def 					_lowerCamelCase(			lowerCAmelCase__				:		Tuple      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	str													=   F.to_tensor(lowerCAmelCase__      )
				SCREAMING_SNAKE_CASE_   :	Optional[int]													=   F.normalize(lowerCAmelCase__    ,    mean=[0.485, 0.456, 0.406]    ,    std=[0.229, 0.224, 0.225]      )
				return image



@torch.no_grad()
def 					_lowerCamelCase(			lowerCAmelCase__				:		Optional[Any]    ,    lowerCAmelCase__				:		str    ,    lowerCAmelCase__				:		List[str]      ):





				'''simple docstring'''







				logger.info('Converting model...'      )

				# load original state dict
				SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   torch.hub.load_state_dict_from_url(lowerCAmelCase__    ,    map_location='cpu'      )
				# rename keys
				for src, dest in rename_keys:
								rename_key(lowerCAmelCase__    ,    lowerCAmelCase__    ,    lowerCAmelCase__      )
				SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   rename_backbone_keys(lowerCAmelCase__      )
				# query, key and value matrices need special treatment
				read_in_q_k_v(lowerCAmelCase__      )
				# important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them
				SCREAMING_SNAKE_CASE_   :	str													=   'model.'
				for key in state_dict.copy().keys():
								if not key.startswith('class_labels_classifier'      ) and not key.startswith('bbox_predictor'      ):
												SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   state_dict.pop(lowerCAmelCase__      )
												SCREAMING_SNAKE_CASE_   :	Any													=   val
    # create HuggingFace model and load state dict
				SCREAMING_SNAKE_CASE_   :	Optional[int]													=   TableTransformerConfig(
				    backbone='resnet18'    ,    mask_loss_coefficient=1    ,    dice_loss_coefficient=1    ,    ce_loss_coefficient=1    ,    bbox_loss_coefficient=5    ,    giou_loss_coefficient=2    ,    eos_coefficient=0.4    ,    class_cost=1    ,    bbox_cost=5    ,    giou_cost=2    ,    )

				if "detection" in checkpoint_url:
								SCREAMING_SNAKE_CASE_   :	int													=   15
								SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   2
								SCREAMING_SNAKE_CASE_   :	int													=   {0: 'table', 1: 'table rotated'}
								SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   idalabel
								SCREAMING_SNAKE_CASE_   :	Any													=   {v: k for k, v in idalabel.items()}
				else:
								SCREAMING_SNAKE_CASE_   :	Tuple													=   125
								SCREAMING_SNAKE_CASE_   :	Dict													=   6
								SCREAMING_SNAKE_CASE_   :	List[Any]													=   {
								    0: 'table',
								    1: 'table column',
								    2: 'table row',
								    3: 'table column header',
								    4: 'table projected row header',
								    5: 'table spanning cell',
								}
								SCREAMING_SNAKE_CASE_   :	Tuple													=   idalabel
								SCREAMING_SNAKE_CASE_   :	List[str]													=   {v: k for k, v in idalabel.items()}

				SCREAMING_SNAKE_CASE_   :	int													=   DetrImageProcessor(
				    format='coco_detection'    ,    max_size=800 if 'detection' in checkpoint_url else 1000      )
				SCREAMING_SNAKE_CASE_   :	List[Any]													=   TableTransformerForObjectDetection(lowerCAmelCase__      )
				model.load_state_dict(lowerCAmelCase__      )
				model.eval()

				# verify our conversion
				SCREAMING_SNAKE_CASE_   :	Dict													=   'example_pdf.png' if 'detection' in checkpoint_url else 'example_table.png'
				SCREAMING_SNAKE_CASE_   :	Optional[int]													=   hf_hub_download(repo_id='nielsr/example-pdf'    ,    repo_type='dataset'    ,    filename=lowerCAmelCase__      )
				SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   Image.open(lowerCAmelCase__      ).convert('RGB'      )
				SCREAMING_SNAKE_CASE_   :	Dict													=   normalize(resize(lowerCAmelCase__    ,    lowerCAmelCase__      )      ).unsqueeze(0      )

				SCREAMING_SNAKE_CASE_   :	Optional[int]													=   model(lowerCAmelCase__      )

				if "detection" in checkpoint_url:
								SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   (1, 15, 3)
								SCREAMING_SNAKE_CASE_   :	Optional[int]													=   torch.tensor(
								    [[-6.7_897, -16.9_985, 6.7_937], [-8.0_186, -22.2_192, 6.9_677], [-7.3_117, -21.0_708, 7.4_055]]      )
								SCREAMING_SNAKE_CASE_   :	List[Any]													=   torch.tensor([[0.4_867, 0.1_767, 0.6_732], [0.6_718, 0.4_479, 0.3_830], [0.4_716, 0.1_760, 0.6_364]]      )

				else:
								SCREAMING_SNAKE_CASE_   :	Dict													=   (1, 125, 7)
								SCREAMING_SNAKE_CASE_   :	int													=   torch.tensor(
								    [[-18.1_430, -8.3_214, 4.8_274], [-18.4_685, -7.1_361, -4.2_667], [-26.3_693, -9.3_429, -4.9_962]]      )
								SCREAMING_SNAKE_CASE_   :	Any													=   torch.tensor([[0.4_983, 0.5_595, 0.9_440], [0.4_916, 0.6_315, 0.5_954], [0.6_108, 0.8_637, 0.1_135]]      )

				assert outputs.logits.shape == expected_shape
				assert torch.allclose(outputs.logits[0, :3, :3]    ,    lowerCAmelCase__    ,    atol=1E-4      )
				assert torch.allclose(outputs.pred_boxes[0, :3, :3]    ,    lowerCAmelCase__    ,    atol=1E-4      )
				print('Looks ok!'      )

				if pytorch_dump_folder_path is not None:
								# Save model and image processor
								logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...'''      )
								Path(lowerCAmelCase__      ).mkdir(exist_ok=lowerCAmelCase__      )
								model.save_pretrained(lowerCAmelCase__      )
								image_processor.save_pretrained(lowerCAmelCase__      )

				if push_to_hub:
								# Push model to HF hub
								logger.info('Pushing model to the hub...'      )
								SCREAMING_SNAKE_CASE_   :	Any													=   (
								    'microsoft/table-transformer-detection'
								    if 'detection' in checkpoint_url
								    else 'microsoft/table-transformer-structure-recognition'
								)
								model.push_to_hub(lowerCAmelCase__      )
								image_processor.push_to_hub(lowerCAmelCase__      )


if __name__ == "__main__":
				A        =			argparse.ArgumentParser()

				parser.add_argument(
				    '--checkpoint_url',
				    default='https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth',
				    type=str,
				    choices=[
				        'https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth',
				        'https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth',
				    ],
				    help='URL of the Table Transformer checkpoint you\'d like to convert.',
				)
				parser.add_argument(
				    '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.'
				)
				parser.add_argument(
				    '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
				)
				A        =			parser.parse_args()
				convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)







import argparse
import os.path as osp
import re

import torch
from safetensors.torch import load_file, save_file


# =================#
# UNet Conversion #
# =================#

A        =			[
    # (stable-diffusion, HF Diffusers)
    ('time_embed.0.weight', 'time_embedding.linear_1.weight'),
    ('time_embed.0.bias', 'time_embedding.linear_1.bias'),
    ('time_embed.2.weight', 'time_embedding.linear_2.weight'),
    ('time_embed.2.bias', 'time_embedding.linear_2.bias'),
    ('input_blocks.0.0.weight', 'conv_in.weight'),
    ('input_blocks.0.0.bias', 'conv_in.bias'),
    ('out.0.weight', 'conv_norm_out.weight'),
    ('out.0.bias', 'conv_norm_out.bias'),
    ('out.2.weight', 'conv_out.weight'),
    ('out.2.bias', 'conv_out.bias'),
]

A        =			[
    # (stable-diffusion, HF Diffusers)
    ('in_layers.0', 'norm1'),
    ('in_layers.2', 'conv1'),
    ('out_layers.0', 'norm2'),
    ('out_layers.3', 'conv2'),
    ('emb_layers.1', 'time_emb_proj'),
    ('skip_connection', 'conv_shortcut'),
]

A        =			[]
# hardcoded number of downblocks and resnets/attentions...
# would need smarter logic for other networks.
for i in range(4):
				# loop over downblocks/upblocks

				for j in range(2):
								# loop over resnets/attentions for downblocks
								A        =			f"""down_blocks.{i}.resnets.{j}."""
								A        =			f"""input_blocks.{3*i + j + 1}.0."""
								unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))

								if i < 3:
												# no attention layers in down_blocks.3
												A        =			f"""down_blocks.{i}.attentions.{j}."""
												A        =			f"""input_blocks.{3*i + j + 1}.1."""
												unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))

				for j in range(3):
								# loop over resnets/attentions for upblocks
								A        =			f"""up_blocks.{i}.resnets.{j}."""
								A        =			f"""output_blocks.{3*i + j}.0."""
								unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))

								if i > 0:
												# no attention layers in up_blocks.0
												A        =			f"""up_blocks.{i}.attentions.{j}."""
												A        =			f"""output_blocks.{3*i + j}.1."""
												unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))

				if i < 3:
								# no downsample in down_blocks.3
								A        =			f"""down_blocks.{i}.downsamplers.0.conv."""
								A        =			f"""input_blocks.{3*(i+1)}.0.op."""
								unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))

								# no upsample in up_blocks.3
								A        =			f"""up_blocks.{i}.upsamplers.0."""
								A        =			f"""output_blocks.{3*i + 2}.{1 if i == 0 else 2}."""
								unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))

A        =			'mid_block.attentions.0.'
A        =			'middle_block.1.'
unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))

for j in range(2):
				A        =			f"""mid_block.resnets.{j}."""
				A        =			f"""middle_block.{2*j}."""
				unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))



def 					_lowerCamelCase(			lowerCAmelCase__				:		Union[str, Any]      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   {k: k for k in unet_state_dict.keys()}
				for sd_name, hf_name in unet_conversion_map:
								SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   sd_name
				for k, v in mapping.items():
								if "resnets" in k:
												for sd_part, hf_part in unet_conversion_map_resnet:
																SCREAMING_SNAKE_CASE_   :	int													=   v.replace(lowerCAmelCase__    ,    lowerCAmelCase__      )
												SCREAMING_SNAKE_CASE_   :	List[str]													=   v
				for k, v in mapping.items():
								for sd_part, hf_part in unet_conversion_map_layer:
												SCREAMING_SNAKE_CASE_   :	str													=   v.replace(lowerCAmelCase__    ,    lowerCAmelCase__      )
								SCREAMING_SNAKE_CASE_   :	Tuple													=   v
				SCREAMING_SNAKE_CASE_   :	str													=   {v: unet_state_dict[k] for k, v in mapping.items()}
				return new_state_dict


# ================#
# VAE Conversion #
# ================#

A        =			[
    # (stable-diffusion, HF Diffusers)
    ('nin_shortcut', 'conv_shortcut'),
    ('norm_out', 'conv_norm_out'),
    ('mid.attn_1.', 'mid_block.attentions.0.'),
]

for i in range(4):
				# down_blocks have two resnets
				for j in range(2):
								A        =			f"""encoder.down_blocks.{i}.resnets.{j}."""
								A        =			f"""encoder.down.{i}.block.{j}."""
								vae_conversion_map.append((sd_down_prefix, hf_down_prefix))

				if i < 3:
								A        =			f"""down_blocks.{i}.downsamplers.0."""
								A        =			f"""down.{i}.downsample."""
								vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))

								A        =			f"""up_blocks.{i}.upsamplers.0."""
								A        =			f"""up.{3-i}.upsample."""
								vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))

				# up_blocks have three resnets
				# also, up blocks in hf are numbered in reverse from sd
				for j in range(3):
								A        =			f"""decoder.up_blocks.{i}.resnets.{j}."""
								A        =			f"""decoder.up.{3-i}.block.{j}."""
								vae_conversion_map.append((sd_up_prefix, hf_up_prefix))

# this part accounts for mid blocks in both the encoder and the decoder
for i in range(2):
				A        =			f"""mid_block.resnets.{i}."""
				A        =			f"""mid.block_{i+1}."""
				vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))


A        =			[
    # (stable-diffusion, HF Diffusers)
    ('norm.', 'group_norm.'),
    ('q.', 'query.'),
    ('k.', 'key.'),
    ('v.', 'value.'),
    ('proj_out.', 'proj_attn.'),
]



def 					_lowerCamelCase(			lowerCAmelCase__				:		List[str]      ):





				'''simple docstring'''







				return w.reshape(*w.shape    ,    1    ,    1      )



def 					_lowerCamelCase(			lowerCAmelCase__				:		int      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	Dict													=   {k: k for k in vae_state_dict.keys()}
				for k, v in mapping.items():
								for sd_part, hf_part in vae_conversion_map:
												SCREAMING_SNAKE_CASE_   :	Any													=   v.replace(lowerCAmelCase__    ,    lowerCAmelCase__      )
								SCREAMING_SNAKE_CASE_   :	int													=   v
				for k, v in mapping.items():
								if "attentions" in k:
												for sd_part, hf_part in vae_conversion_map_attn:
																SCREAMING_SNAKE_CASE_   :	Dict													=   v.replace(lowerCAmelCase__    ,    lowerCAmelCase__      )
												SCREAMING_SNAKE_CASE_   :	Tuple													=   v
				SCREAMING_SNAKE_CASE_   :	Dict													=   {v: vae_state_dict[k] for k, v in mapping.items()}
				SCREAMING_SNAKE_CASE_   :	int													=   ['q', 'k', 'v', 'proj_out']
				for k, v in new_state_dict.items():
								for weight_name in weights_to_convert:
												if F'''mid.attn_1.{weight_name}.weight''' in k:
																print(F'''Reshaping {k} for SD format'''      )
																SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   reshape_weight_for_sd(lowerCAmelCase__      )
				return new_state_dict


# =========================#
# Text Encoder Conversion #
# =========================#


A        =			[
    # (stable-diffusion, HF Diffusers)
    ('resblocks.', 'text_model.encoder.layers.'),
    ('ln_1', 'layer_norm1'),
    ('ln_2', 'layer_norm2'),
    ('.c_fc.', '.fc1.'),
    ('.c_proj.', '.fc2.'),
    ('.attn', '.self_attn'),
    ('ln_final.', 'transformer.text_model.final_layer_norm.'),
    ('token_embedding.weight', 'transformer.text_model.embeddings.token_embedding.weight'),
    ('positional_embedding', 'transformer.text_model.embeddings.position_embedding.weight'),
]
A        =			{re.escape(x[1]): x[0] for x in textenc_conversion_lst}
A        =			re.compile('|'.join(protected.keys()))

# Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp
A        =			{'q': 0, 'k': 1, 'v': 2}



def 					_lowerCamelCase(			lowerCAmelCase__				:		List[Any]      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   {}
				SCREAMING_SNAKE_CASE_   :	List[str]													=   {}
				SCREAMING_SNAKE_CASE_   :	Any													=   {}
				for k, v in text_enc_dict.items():
								if (
								    k.endswith('.self_attn.q_proj.weight'      )
								    or k.endswith('.self_attn.k_proj.weight'      )
								    or k.endswith('.self_attn.v_proj.weight'      )
								):
												SCREAMING_SNAKE_CASE_   :	int													=   k[: -len('.q_proj.weight'      )]
												SCREAMING_SNAKE_CASE_   :	List[str]													=   k[-len('q_proj.weight'      )]
												if k_pre not in capture_qkv_weight:
																SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   [None, None, None]
												SCREAMING_SNAKE_CASE_   :	int													=   v
												continue

								if (
								    k.endswith('.self_attn.q_proj.bias'      )
								    or k.endswith('.self_attn.k_proj.bias'      )
								    or k.endswith('.self_attn.v_proj.bias'      )
								):
												SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   k[: -len('.q_proj.bias'      )]
												SCREAMING_SNAKE_CASE_   :	str													=   k[-len('q_proj.bias'      )]
												if k_pre not in capture_qkv_bias:
																SCREAMING_SNAKE_CASE_   :	Tuple													=   [None, None, None]
												SCREAMING_SNAKE_CASE_   :	Any													=   v
												continue

								SCREAMING_SNAKE_CASE_   :	Tuple													=   textenc_pattern.sub(lambda lowerCAmelCase__      : protected[re.escape(m.group(0      )      )]    ,    lowerCAmelCase__      )
								SCREAMING_SNAKE_CASE_   :	Any													=   v

				for k_pre, tensors in capture_qkv_weight.items():
								if None in tensors:
												raise Exception('CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing'      )
								SCREAMING_SNAKE_CASE_   :	Dict													=   textenc_pattern.sub(lambda lowerCAmelCase__      : protected[re.escape(m.group(0      )      )]    ,    lowerCAmelCase__      )
								SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   torch.cat(lowerCAmelCase__      )

				for k_pre, tensors in capture_qkv_bias.items():
								if None in tensors:
												raise Exception('CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing'      )
								SCREAMING_SNAKE_CASE_   :	Optional[int]													=   textenc_pattern.sub(lambda lowerCAmelCase__      : protected[re.escape(m.group(0      )      )]    ,    lowerCAmelCase__      )
								SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   torch.cat(lowerCAmelCase__      )

				return new_state_dict



def 					_lowerCamelCase(			lowerCAmelCase__				:		Optional[Any]      ):





				'''simple docstring'''







				return text_enc_dict


if __name__ == "__main__":
				A        =			argparse.ArgumentParser()

				parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.')
				parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.')
				parser.add_argument('--half', action='store_true', help='Save weights in half precision.')
				parser.add_argument(
				    '--use_safetensors', action='store_true', help='Save weights use safetensors, default is ckpt.'
				)

				A        =			parser.parse_args()

				assert args.model_path is not None, "Must provide a model path!"

				assert args.checkpoint_path is not None, "Must provide a checkpoint path!"

				# Path for safetensors
				A        =			osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.safetensors')
				A        =			osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.safetensors')
				A        =			osp.join(args.model_path, 'text_encoder', 'model.safetensors')

				# Load models from safetensors if it exists, if it doesn't pytorch
				if osp.exists(unet_path):
								A        =			load_file(unet_path, device='cpu')
				else:
								A        =			osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.bin')
								A        =			torch.load(unet_path, map_location='cpu')

				if osp.exists(vae_path):
								A        =			load_file(vae_path, device='cpu')
				else:
								A        =			osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.bin')
								A        =			torch.load(vae_path, map_location='cpu')

				if osp.exists(text_enc_path):
								A        =			load_file(text_enc_path, device='cpu')
				else:
								A        =			osp.join(args.model_path, 'text_encoder', 'pytorch_model.bin')
								A        =			torch.load(text_enc_path, map_location='cpu')

				# Convert the UNet model
				A        =			convert_unet_state_dict(unet_state_dict)
				A        =			{'model.diffusion_model.' + k: v for k, v in unet_state_dict.items()}

				# Convert the VAE model
				A        =			convert_vae_state_dict(vae_state_dict)
				A        =			{'first_stage_model.' + k: v for k, v in vae_state_dict.items()}

				# Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper
				A        =			'text_model.encoder.layers.22.layer_norm2.bias' in text_enc_dict

				if is_vaa_model:
								# Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm
								A        =			{'transformer.' + k: v for k, v in text_enc_dict.items()}
								A        =			convert_text_enc_state_dict_vaa(text_enc_dict)
								A        =			{'cond_stage_model.model.' + k: v for k, v in text_enc_dict.items()}
				else:
								A        =			convert_text_enc_state_dict(text_enc_dict)
								A        =			{'cond_stage_model.transformer.' + k: v for k, v in text_enc_dict.items()}

				# Put together new checkpoint
				A        =			{**unet_state_dict, **vae_state_dict, **text_enc_dict}
				if args.half:
								A        =			{k: v.half() for k, v in state_dict.items()}

				if args.use_safetensors:
								save_file(state_dict, args.checkpoint_path)
				else:
								A        =			{'state_dict': state_dict}
								torch.save(state_dict, args.checkpoint_path)